diff --git a/external/CMakeLists.txt b/external/CMakeLists.txt index 959ca0f..ce28bb8 100644 --- a/external/CMakeLists.txt +++ b/external/CMakeLists.txt @@ -2,6 +2,7 @@ add_subdirectory(sqlite3/sqlite-3430000) add_subdirectory(goahead-5.2.0) +# ================= httpserver ================= # find_program(M4 m4) if(NOT M4) message("m4 not found. Install before continuing.") @@ -15,5 +16,7 @@ if(NOT RAGEL) WORKING_DIRECTORY ${EXTERNAL_SOURCE_PATH}/gtest/) endif() add_subdirectory(httpserver.h-master/src) +# ================= httpserver end ================= # -add_subdirectory(cJSON-1.7.17) \ No newline at end of file +add_subdirectory(cJSON-1.7.17) +add_subdirectory(libhv/libhv-1.3.2) \ No newline at end of file diff --git a/external/libhv/libhv-1.3.2/.clang-format b/external/libhv/libhv-1.3.2/.clang-format new file mode 100644 index 0000000..80d5c60 --- /dev/null +++ b/external/libhv/libhv-1.3.2/.clang-format @@ -0,0 +1,95 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: true +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: true +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 + BeforeCatch: true + BeforeElse: true + IndentBraces: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 160 +CommentPragmas: '^ IWYU pragma:' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: true +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeCategories: + - Regex: '.*' + Priority: 1 + - Regex: '^".*/' + Priority: 2 + - Regex: '^<)' + Priority: 3 +IncludeIsMainRegex: '$' +IndentCaseLabels: false +IndentWidth: 4 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 4 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +ReflowComments: true +SortIncludes: false +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 4 +UseTab: Never +... + diff --git a/external/libhv/libhv-1.3.2/.gitattributes b/external/libhv/libhv-1.3.2/.gitattributes new file mode 100644 index 0000000..2512879 --- /dev/null +++ b/external/libhv/libhv-1.3.2/.gitattributes @@ -0,0 +1 @@ +cpputil/json.hpp linguist-vendored diff --git a/external/libhv/libhv-1.3.2/.gitignore b/external/libhv/libhv-1.3.2/.gitignore new file mode 100644 index 0000000..1025ed5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/.gitignore @@ -0,0 +1,72 @@ +# Compiled Object files +*.o +*.lo +*.slo +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Compiled Static libraries +*.a +*.la +*.lai +*.lib + +# Executables +*.exe +*.out +*.app + +# cache +*~ +*.bk +*.bak +*.old +*.new + +# IDE +.vs +.vscode +.DS_Store + +tags +cscope* +.ycm* + +# generated +examples/protorpc/generated + +# output +*.pid +*.log +*.db + +include +lib +bin +tmp +dist +test +*_test +build +config.mk +hconfig.h +html/uploads + +# msvc +*.VC.* +*.vcxproj.* +Debug +Release + +# cmake +CMakeFiles +CMakeCache.txt +cmake_install.cmake diff --git a/external/libhv/libhv-1.3.2/.travis.yml b/external/libhv/libhv-1.3.2/.travis.yml new file mode 100644 index 0000000..6bd4ad3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/.travis.yml @@ -0,0 +1,39 @@ +language: cpp + +jobs: + include: + - os: linux + dist: xenial + compiler: gcc + env: COVERALLS=no + script: + - ./configure + - make libhv examples unittest evpp + + - os: osx + compiler: clang + env: COVERALLS=no + script: + - ./configure + - make libhv examples unittest evpp + + - os: windows + compiler: msvc + env: COVERALLS=no + script: + - mkdir win64 + - cd win64 + - cmake .. -G "Visual Studio 15 2017 Win64" + - cmake --build . + +before_script: + - if [ "$COVERALLS" = "yes" ]; then + pip install --user cpp-coveralls; + export CC="$CC --coverage" CXX="$CXX --coverage"; + fi + +after_success: + - if [ "$COVERALLS" = "yes" ]; then + scripts/test-coverage.sh; + coveralls --gcov-options '\-lp' --include base --include event --include http; + fi diff --git a/external/libhv/libhv-1.3.2/BUILD.md b/external/libhv/libhv-1.3.2/BUILD.md new file mode 100644 index 0000000..2b0e931 --- /dev/null +++ b/external/libhv/libhv-1.3.2/BUILD.md @@ -0,0 +1,156 @@ +## Prequired + +- c99 +- c++11 + +gcc4.8+, msvc2015 or later + +## Makefile +options see [config.ini](config.ini) +``` +./configure --with-openssl +make +sudo make install +``` + +## cmake +options see [CMakeLists.txt](CMakeLists.txt) +``` +mkdir build +cd build +cmake .. -DWITH_OPENSSL=ON +cmake --build . +``` + +## Unix +use Makefile or cmake + +## Windows +use cmake +``` +mkdir win64 +cd win64 +cmake .. -G "Visual Studio 15 2017 Win64" +#cmake .. -G "Visual Studio 16 2019" -A x64 +#cmake .. -G "Visual Studio 17 2022" -A x64 +cmake --build . +``` + +## CROSS_COMPILE +use Makefile +``` +sudo apt install gcc-arm-linux-gnueabi g++-arm-linux-gnueabi # ubuntu +export CROSS_COMPILE=arm-linux-gnueabi- +./configure +make clean +make libhv +``` +or use cmake +``` +mkdir build +cd build +cmake .. -DCMAKE_C_COMPILER=arm-linux-gnueabi-gcc -DCMAKE_CXX_COMPILER=arm-linux-gnueabi-g++ +cmake --build . --target libhv libhv_static +``` + +### mingw +see CROSS_COMPILE +``` +sudo apt install mingw-w64 # ubuntu +#export CROSS_COMPILE=i686-w64-mingw32- +export CROSS_COMPILE=x86_64-w64-mingw32- +./configure +make clean +make libhv +``` + +### Android +``` +#https://developer.android.com/ndk/downloads +#export ANDROID_NDK_ROOT=~/Downloads/android-ndk-r21b +mkdir build +cd build +cmake .. -DCMAKE_TOOLCHAIN_FILE="$ANDROID_NDK_ROOT/build/cmake/android.toolchain.cmake" -DANDROID_ABI="arm64-v8a" -DANDROID_PLATFORM=android-21 +cmake --build . --target hv --config Release +``` + +### iOS +``` +mkdir build +cd build +cmake .. -G Xcode -DCMAKE_TOOLCHAIN_FILE=../cmake/ios.toolchain.cmake -DPLATFORM=OS64 -DARCHS="arm64" -DDEPLOYMENT_TARGET=9.0 +cmake --build . --target hv_static --config Release +``` + +## targets + +### lib +- make libhv + +### examples +- make examples + +### unittest +- make unittest + +## options + +### compile without c++ +``` +./configure --without-evpp +make clean && make libhv +``` + +### compile WITH_OPENSSL +Enable SSL/TLS in libhv is so easy :) +``` +// see ssl/hssl.h +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt); + +// see event/hloop.h +int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); +``` + +https is the best example. +``` +sudo apt install openssl libssl-dev # ubuntu +./configure --with-openssl +make clean && make +bin/httpd -s restart -d +bin/curl -v http://localhost:8080 +bin/curl -v https://localhost:8443 +``` + +### compile WITH_CURL +``` +./configure --with-curl +make clean && make +bin/httpd -s restart -d +bin/curl -v http://localhost:8080 +``` + +### compile WITH_NGHTTP2 +``` +sudo apt install libnghttp2-dev # ubuntu +./configure --with-nghttp2 +make clean && make +bin/httpd -s restart -d +bin/curl -v http://localhost:8080 --http2 +``` + +### compile WITH_KCP +``` +./configure --with-kcp +make clean && make +``` + +### compile WITH_MQTT +``` +./configure --with-mqtt +make clean && make +``` + +### More +``` +./configure --help +``` diff --git a/external/libhv/libhv-1.3.2/CMakeLists.txt b/external/libhv/libhv-1.3.2/CMakeLists.txt new file mode 100644 index 0000000..b7e7ff0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/CMakeLists.txt @@ -0,0 +1,281 @@ +cmake_minimum_required(VERSION 3.6) + +project(hv VERSION 1.3.2) + +option(BUILD_SHARED "build shared library" ON) +option(BUILD_STATIC "build static library" ON) + +option(BUILD_EXAMPLES "build examples" ON) +option(BUILD_UNITTEST "build unittest" OFF) + +# see config.ini +option(WITH_PROTOCOL "compile protocol" OFF) + +option(WITH_EVPP "compile evpp" ON) +option(WITH_HTTP "compile http" ON) +option(WITH_HTTP_SERVER "compile http/server" ON) +option(WITH_HTTP_CLIENT "compile http/client" ON) +option(WITH_MQTT "compile mqtt" OFF) + +option(ENABLE_UDS "Unix Domain Socket" OFF) +option(USE_MULTIMAP "MultiMap" OFF) + +option(WITH_CURL "with curl library (deprecated)" OFF) +option(WITH_NGHTTP2 "with nghttp2 library" OFF) + +option(WITH_OPENSSL "with openssl library" OFF) +option(WITH_GNUTLS "with gnutls library" OFF) +option(WITH_MBEDTLS "with mbedtls library" OFF) + +option(WITH_KCP "compile event/kcp" OFF) + +if(WIN32) + option(WITH_WEPOLL "compile event/wepoll -> use iocp" ON) + option(ENABLE_WINDUMP "Windows MiniDumpWriteDump" OFF) + option(BUILD_FOR_MT "build for /MT" OFF) + if(BUILD_FOR_MT) + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd") + set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd") + set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT") + set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT") + endif() +endif() + +message(STATUS "CMAKE_SOURCE_DIR=${CMAKE_SOURCE_DIR}") +message(STATUS "CMAKE_CURRENT_SOURCE_DIR=${CMAKE_CURRENT_SOURCE_DIR}") +if(NOT "${CMAKE_CURRENT_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}") + set(BUILD_EXAMPLES OFF) +endif() + +if(IOS) + set(BUILD_SHARED OFF) + set(BUILD_EXAMPLES OFF) +endif() + +set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") +include(utils) +include(vars) + +# see configure +# Checks for header files +check_header("stdbool.h") +check_header("stdint.h") +check_header("stdatomic.h") +check_header("sys/types.h") +check_header("sys/stat.h") +check_header("sys/time.h") +check_header("fcntl.h") +check_header("pthread.h") +check_header("endian.h") +check_header("sys/endian.h") + +# Checks for functions +if(NOT MSVC) + set(CMAKE_REQUIRED_LIBRARIES "-pthread") +endif() +check_function("gettid" "unistd.h") +check_function("strlcpy" "string.h") +check_function("strlcat" "string.h") +check_function("clock_gettime" "time.h") +check_function("gettimeofday" "sys/time.h") +check_function("pthread_spin_lock" "pthread.h") +check_function("pthread_mutex_timedlock" "pthread.h") +check_function("sem_timedwait" "semaphore.h") +check_function("pipe" "unistd.h") +check_function("socketpair" "sys/socket.h") +check_function("eventfd" "sys/eventfd.h") +check_function("setproctitle" "unistd.h") + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/hconfig.h.in ${CMAKE_CURRENT_SOURCE_DIR}/hconfig.h) + +# see Makefile.in +set(CMAKE_C_STANDARD 99) +set(CMAKE_C_STANDARD_REQUIRED True) +set(CMAKE_CXX_STANDARD 11) +set(CMAKE_CXX_STANDARD_REQUIRED True) + +set(INCDIR include) +set(SRCDIR src) +set(LIBDIR lib) +set(BINDIR bin) +set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${LIBDIR}) +set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${LIBDIR}) +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${BINDIR}) +message(STATUS "CMAKE_LIBRARY_OUTPUT_DIRECTORY=${CMAKE_LIBRARY_OUTPUT_DIRECTORY}") + +set(INCDIRS . include 3rd/include) +set(LIBDIRS . lib 3rd/lib) +include_directories(${INCDIRS} ${SRCDIR}) +link_directories(${LIBDIRS}) + +message(STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") +if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug") + add_definitions(-DDEBUG) +else() + add_definitions(-DNDEBUG) +endif() + +if(ENABLE_UDS) + add_definitions(-DENABLE_UDS) +endif() + +if(USE_MULTIMAP) + add_definitions(-DUSE_MULTIMAP) +endif() + +if(WITH_CURL) + add_definitions(-DWITH_CURL) + set(LIBS ${LIBS} curl) + if(WIN32) + set(LIBS ${LIBS} wldap32 advapi32 crypt32) + endif() +endif() + +if(WITH_NGHTTP2) + add_definitions(-DWITH_NGHTTP2) + set(LIBS ${LIBS} nghttp2) +endif() + +if(WITH_OPENSSL) + add_definitions(-DWITH_OPENSSL) + find_package(OpenSSL) + if(OpenSSL_FOUND) + set(LIBS ${LIBS} OpenSSL::SSL OpenSSL::Crypto) + else() + set(LIBS ${LIBS} ssl crypto) + endif() +endif() + +if(WITH_GNUTLS) + add_definitions(-DWITH_GNUTLS) + set(LIBS ${LIBS} gnutls) +endif() + +if(WITH_MBEDTLS) + add_definitions(-DWITH_MBEDTLS) + set(LIBS ${LIBS} mbedtls mbedx509 mbedcrypto) +endif() + +if(WIN32) + add_definitions(-DWIN32_LEAN_AND_MEAN -D_CRT_SECURE_NO_WARNINGS -D_WIN32_WINNT=0x0600) + set(LIBS ${LIBS} secur32 crypt32 winmm iphlpapi ws2_32) + if(ENABLE_WINDUMP) + add_definitions(-DENABLE_WINDUMP) + set(LIBS ${LIBS} dbghelp) + endif() +endif() + +if(ANDROID) + set(LIBS ${LIBS} log) +elseif(UNIX) + set(LIBS ${LIBS} pthread m dl) + if(CMAKE_COMPILER_IS_GNUCC) + set(LIBS ${LIBS} rt) + endif() +endif() + +if(APPLE) + set(LIBS ${LIBS} "-framework CoreFoundation" "-framework Security") +endif() + +# see Makefile +set(ALL_SRCDIRS . base ssl event event/kcp util cpputil evpp protocol http http/client http/server mqtt) +set(CORE_SRCDIRS . base ssl event) +if(WIN32) + if(WITH_WEPOLL) + set(CORE_SRCDIRS ${CORE_SRCDIRS} event/wepoll) + endif() +endif() +if(WITH_KCP) + set(CORE_SRCDIRS ${CORE_SRCDIRS} event/kcp) +endif() +set(LIBHV_SRCDIRS ${CORE_SRCDIRS} util) +set(LIBHV_HEADERS hv.h hconfig.h hexport.h) +set(LIBHV_HEADERS ${LIBHV_HEADERS} ${BASE_HEADERS} ${SSL_HEADERS} ${EVENT_HEADERS} ${UTIL_HEADERS}) + +if(WITH_PROTOCOL) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${PROTOCOL_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} protocol) +endif() + +if(WITH_EVPP) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${CPPUTIL_HEADERS} ${EVPP_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} cpputil evpp) + if(WITH_HTTP) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http) + if(WITH_NGHTTP2) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP2_HEADERS}) + endif() + if(WITH_HTTP_SERVER) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_SERVER_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http/server) + endif() + if(WITH_HTTP_CLIENT) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${HTTP_CLIENT_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} http/client) + endif() + endif() + + if(CMAKE_SYSTEM_NAME MATCHES "Linux" AND CMAKE_COMPILER_IS_GNUCC) + set(LIBS ${LIBS} stdc++) + endif() +endif() + +if(WITH_MQTT) + set(LIBHV_HEADERS ${LIBHV_HEADERS} ${MQTT_HEADERS}) + set(LIBHV_SRCDIRS ${LIBHV_SRCDIRS} mqtt) +endif() + +list_source_directories(LIBHV_SRCS ${LIBHV_SRCDIRS}) + +file(INSTALL ${LIBHV_HEADERS} DESTINATION include/hv) +file(INSTALL ${LIBHV_HEADERS} DESTINATION ${PROJECT_SOURCE_DIR}/include/hv) + +if(BUILD_SHARED) + add_library(hv SHARED ${LIBHV_SRCS}) + target_compile_definitions(hv PRIVATE HV_DYNAMICLIB) + target_include_directories(hv PRIVATE ${LIBHV_SRCDIRS} + INTERFACE $ $) + target_link_libraries(hv ${LIBS}) + install(TARGETS hv + EXPORT libhvConfig + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin) + add_custom_target(libhv DEPENDS hv) +endif() + +if(BUILD_STATIC) + add_library(hv_static STATIC ${LIBHV_SRCS}) + target_compile_definitions(hv_static PUBLIC HV_STATICLIB) + target_include_directories(hv_static PRIVATE ${LIBHV_SRCDIRS} + INTERFACE $ $) + target_link_libraries(hv_static ${LIBS}) + install(TARGETS hv_static + EXPORT libhvConfig + ARCHIVE DESTINATION lib) + add_custom_target(libhv_static DEPENDS hv_static) +endif() + +install(FILES ${LIBHV_HEADERS} DESTINATION include/hv) +install(EXPORT libhvConfig DESTINATION lib/cmake/libhv) + +if(BUILD_SHARED) + set(HV_LIBRARIES hv CACHE INTERNAL "link hv libraries") +else() + add_definitions(-DHV_STATICLIB) + set(HV_LIBRARIES hv_static ${LIBS} CACHE INTERNAL "link hv libraries") +endif() + +if(BUILD_EXAMPLES) + add_subdirectory(examples) + # for httpd -c etc/httpd.conf + file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}) + file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}/bin) + file(INSTALL etc DESTINATION ${CMAKE_BINARY_DIR}/examples) +endif() + +if(BUILD_UNITTEST) + add_subdirectory(unittest) +endif() diff --git a/external/libhv/libhv-1.3.2/LICENSE b/external/libhv/libhv-1.3.2/LICENSE new file mode 100644 index 0000000..77c29c1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/LICENSE @@ -0,0 +1,30 @@ +BSD 3-Clause License + +Copyright (c) 2020, ithewei +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 the 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 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 HOLDER 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/external/libhv/libhv-1.3.2/Makefile b/external/libhv/libhv-1.3.2/Makefile new file mode 100644 index 0000000..a875f99 --- /dev/null +++ b/external/libhv/libhv-1.3.2/Makefile @@ -0,0 +1,283 @@ +include config.mk +include Makefile.vars + +MAKEF=$(MAKE) -f Makefile.in +ALL_SRCDIRS=. base ssl event event/kcp util cpputil evpp protocol http http/client http/server mqtt +CORE_SRCDIRS=. base ssl event +ifeq ($(WITH_KCP), yes) +CORE_SRCDIRS += event/kcp +endif + +LIBHV_SRCDIRS = $(CORE_SRCDIRS) util +LIBHV_HEADERS = hv.h hconfig.h hexport.h +LIBHV_HEADERS += $(BASE_HEADERS) $(SSL_HEADERS) $(EVENT_HEADERS) $(UTIL_HEADERS) + +ifeq ($(WITH_PROTOCOL), yes) +LIBHV_HEADERS += $(PROTOCOL_HEADERS) +LIBHV_SRCDIRS += protocol +endif + +ifeq ($(WITH_EVPP), yes) +LIBHV_HEADERS += $(CPPUTIL_HEADERS) $(EVPP_HEADERS) +LIBHV_SRCDIRS += cpputil evpp + +ifeq ($(WITH_HTTP), yes) +LIBHV_HEADERS += $(HTTP_HEADERS) +LIBHV_SRCDIRS += http + +ifeq ($(WITH_NGHTTP2), yes) +LIBHV_HEADERS += $(HTTP2_HEADERS) +endif + +ifeq ($(WITH_HTTP_SERVER), yes) +LIBHV_HEADERS += $(HTTP_SERVER_HEADERS) +LIBHV_SRCDIRS += http/server +endif + +ifeq ($(WITH_HTTP_CLIENT), yes) +LIBHV_HEADERS += $(HTTP_CLIENT_HEADERS) +LIBHV_SRCDIRS += http/client +endif + +endif +endif + +ifeq ($(WITH_MQTT), yes) +LIBHV_HEADERS += $(MQTT_HEADERS) +LIBHV_SRCDIRS += mqtt +endif + +default: all + +all: libhv examples + @echo "make all done, please enjoy libhv." + +examples: hmain_test htimer_test hloop_test \ + nc nmap tinyhttpd tinyproxyd httpd curl wget wrk consul \ + tcp_client_test \ + tcp_echo_server \ + tcp_chat_server \ + tcp_proxy_server \ + udp_echo_server \ + udp_proxy_server \ + socks5_proxy_server \ + multi-acceptor-processes \ + multi-acceptor-threads \ + one-acceptor-multi-workers \ + http_server_test http_client_test \ + websocket_server_test \ + websocket_client_test \ + mqtt_sub \ + mqtt_pub \ + mqtt_client_test \ + jsonrpc + @echo "make examples done." + +clean: + $(MAKEF) clean SRCDIRS="$(ALL_SRCDIRS)" + $(RM) examples/*.o examples/*/*.o + $(RM) include/hv + @echo "make clean done." + +prepare: + $(MKDIR) bin + +libhv: + $(MKDIR) lib + $(MAKEF) TARGET=$@ TARGET_TYPE="SHARED|STATIC" SRCDIRS="$(LIBHV_SRCDIRS)" + $(MKDIR) include/hv + $(CP) $(LIBHV_HEADERS) include/hv + @echo "make libhv done." + +install: + $(MKDIR) $(INSTALL_INCDIR) + $(MKDIR) $(INSTALL_LIBDIR) + $(CP) include/hv/* $(INSTALL_INCDIR) + $(CP) lib/libhv.* $(INSTALL_LIBDIR) + $(LDCONFIG) + @echo "make install done." + +uninstall: clean + $(RM) $(PREFIX)/include/hv + $(RM) $(PREFIX)/lib/libhv.* + @echo "make uninstall done." + +hmain_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS=". base cpputil" SRCS="examples/hmain_test.cpp" + +htimer_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/htimer_test.c" + +hloop_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/hloop_test.c" + +tcp_client_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tcp_client_test.c" + +tcp_echo_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tcp_echo_server.c" + +tcp_chat_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tcp_chat_server.c" + +tcp_proxy_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tcp_proxy_server.c" + +udp_echo_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/udp_echo_server.c" + +udp_proxy_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/udp_proxy_server.c" + +socks5_proxy_server: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/socks5_proxy_server.c" + +multi-acceptor-processes: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/multi-thread/multi-acceptor-processes.c" + +multi-acceptor-threads: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/multi-thread/multi-acceptor-threads.c" + +one-acceptor-multi-workers: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/multi-thread/one-acceptor-multi-workers.c" + +nc: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/nc.c" + +tinyhttpd: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tinyhttpd.c" + +tinyproxyd: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/tinyproxyd.c" + +nmap: prepare libhv + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) cpputil examples/nmap" DEFINES="PRINT_DEBUG" + +wrk: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http" SRCS="examples/wrk.cpp" + +httpd: prepare + $(RM) examples/httpd/*.o + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client http/server examples/httpd" + +consul: prepare libhv + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client examples/consul" DEFINES="PRINT_DEBUG" + +curl: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client" SRCS="examples/curl.cpp" + # $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client" SRCS="examples/curl.cpp" WITH_CURL=yes + +wget: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client" SRCS="examples/wget.cpp" + +http_server_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/server" SRCS="examples/http_server_test.cpp" + +http_client_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client" SRCS="examples/http_client_test.cpp" + +websocket_server_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/server" SRCS="examples/websocket_server_test.cpp" + +websocket_client_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) util cpputil evpp http http/client" SRCS="examples/websocket_client_test.cpp" + +mqtt_sub: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) mqtt" SRCS="examples/mqtt/mqtt_sub.c" + +mqtt_pub: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) mqtt" SRCS="examples/mqtt/mqtt_pub.c" + +mqtt_client_test: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) mqtt" SRCS="examples/mqtt/mqtt_client_test.cpp" + +jsonrpc: jsonrpc_client jsonrpc_server + +jsonrpc_client: prepare + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/jsonrpc/jsonrpc_client.c examples/jsonrpc/cJSON.c" + +jsonrpc_server: prepare + $(RM) examples/jsonrpc/*.o + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS)" SRCS="examples/jsonrpc/jsonrpc_server.c examples/jsonrpc/cJSON.c" + +protorpc: protorpc_client protorpc_server + +protorpc_protoc: + bash examples/protorpc/proto/protoc.sh + +protorpc_client: prepare protorpc_protoc + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) cpputil evpp examples/protorpc/generated" \ + SRCS="examples/protorpc/protorpc_client.cpp examples/protorpc/protorpc.c" \ + LIBS="protobuf" + +protorpc_server: prepare protorpc_protoc + $(RM) examples/protorpc/*.o + $(MAKEF) TARGET=$@ SRCDIRS="$(CORE_SRCDIRS) cpputil evpp examples/protorpc/generated" \ + SRCS="examples/protorpc/protorpc_server.cpp examples/protorpc/protorpc.c" \ + LIBS="protobuf" + +unittest: prepare + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/rbtree_test unittest/rbtree_test.c base/rbtree.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/hbase_test unittest/hbase_test.c base/hbase.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/mkdir_p unittest/mkdir_test.c base/hbase.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/rmdir_p unittest/rmdir_test.c base/hbase.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/date unittest/date_test.c base/htime.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/hatomic_test unittest/hatomic_test.c -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -o bin/hatomic_cpp_test unittest/hatomic_test.cpp -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -o bin/hthread_test unittest/hthread_test.cpp -pthread + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/hmutex_test unittest/hmutex_test.c base/htime.c -pthread + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/connect_test unittest/connect_test.c base/hsocket.c base/htime.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -o bin/socketpair_test unittest/socketpair_test.c base/hsocket.c + $(CC) -g -Wall -O0 -std=c99 -I. -Iutil -o bin/base64 unittest/base64_test.c util/base64.c + $(CC) -g -Wall -O0 -std=c99 -I. -Iutil -o bin/md5 unittest/md5_test.c util/md5.c + $(CC) -g -Wall -O0 -std=c99 -I. -Iutil -o bin/sha1 unittest/sha1_test.c util/sha1.c + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/hstring_test unittest/hstring_test.cpp cpputil/hstring.cpp + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/hpath_test unittest/hpath_test.cpp cpputil/hpath.cpp + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/hurl_test unittest/hurl_test.cpp cpputil/hurl.cpp base/hbase.c + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/ls unittest/listdir_test.cpp cpputil/hdir.cpp + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/ifconfig unittest/ifconfig_test.cpp cpputil/ifconfig.cpp + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/defer_test unittest/defer_test.cpp + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/synchronized_test unittest/synchronized_test.cpp -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/threadpool_test unittest/threadpool_test.cpp -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Icpputil -o bin/objectpool_test unittest/objectpool_test.cpp -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Ievpp -Icpputil -Ihttp -Ihttp/client -Ihttp/server -o bin/sizeof_test unittest/sizeof_test.cpp + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -Iprotocol -o bin/nslookup unittest/nslookup_test.c protocol/dns.c base/hsocket.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -Iprotocol -o bin/ping unittest/ping_test.c protocol/icmp.c base/hsocket.c base/htime.c -DPRINT_DEBUG + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -Iprotocol -o bin/ftp unittest/ftp_test.c protocol/ftp.c base/hsocket.c + $(CC) -g -Wall -O0 -std=c99 -I. -Ibase -Iprotocol -Iutil -o bin/sendmail unittest/sendmail_test.c protocol/smtp.c base/hsocket.c util/base64.c + +run-unittest: unittest + bash scripts/unittest.sh + +check: examples + bash scripts/check.sh + +evpp: prepare libhv + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/EventLoop_test evpp/EventLoop_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/EventLoopThread_test evpp/EventLoopThread_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/EventLoopThreadPool_test evpp/EventLoopThreadPool_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/TimerThread_test evpp/TimerThread_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/TcpServer_test evpp/TcpServer_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/TcpClient_test evpp/TcpClient_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/TcpClientEventLoop_test evpp/TcpClientEventLoop_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/UdpServer_test evpp/UdpServer_test.cpp -Llib -lhv -pthread + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -o bin/UdpClient_test evpp/UdpClient_test.cpp -Llib -lhv -pthread + +# UNIX only +webbench: prepare + $(CC) -o bin/webbench unittest/webbench.c + +echo-servers: + $(CXX) -g -Wall -std=c++11 -O3 -o bin/pingpong_client echo-servers/pingpong_client.cpp -lhv -pthread + $(CC) -g -Wall -std=c99 -O3 -o bin/libevent_echo echo-servers/libevent_echo.c -levent + $(CC) -g -Wall -std=c99 -O3 -o bin/libev_echo echo-servers/libev_echo.c -lev + $(CC) -g -Wall -std=c99 -O3 -o bin/libuv_echo echo-servers/libuv_echo.c -luv + $(CC) -g -Wall -std=c99 -O3 -o bin/libhv_echo echo-servers/libhv_echo.c -lhv + $(CXX) -g -Wall -std=c++11 -O3 -o bin/asio_echo echo-servers/asio_echo.cpp -lboost_system -pthread + $(CXX) -g -Wall -std=c++11 -O3 -o bin/poco_echo echo-servers/poco_echo.cpp -lPocoNet -lPocoUtil -lPocoFoundation +# $(CXX) -g -Wall -std=c++11 -O3 -o bin/muduo_echo echo-servers/muduo_echo.cpp -lmuduo_net -lmuduo_base -pthread + +echo-benchmark: echo-servers + bash echo-servers/benchmark.sh + +.PHONY: clean prepare install uninstall libhv examples unittest evpp echo-servers diff --git a/external/libhv/libhv-1.3.2/Makefile.in b/external/libhv/libhv-1.3.2/Makefile.in new file mode 100644 index 0000000..6cf6ee0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/Makefile.in @@ -0,0 +1,306 @@ +#+++++++++++++++++++++++++++++++++configure++++++++++++++++++++++++++++++++++++++++ +# OS=Windows,Linux,Android +# ARCH=x86,x86_64,arm,aarch64 +# CC = $(CROSS_COMPILE)gcc +# CXX = $(CROSS_COMPILE)g++ +# CPPFLAGS += $(addprefix -D, $(DEFINES)) +# CPPFLAGS += $(addprefix -I, $(SRCDIRS)) +# CPPFLAGS += $(addprefix -I, $(INCDIRS)) +# LDFLAGS += $(addprefix -L, $(LIBDIRS)) +# LDFLAGS += $(addprefix -l, $(LIBS)) +# +# Usage: +# make all \ +# TARGET=libxx \ +# TARGET_TYPE=SHARED \ +# BUILD_TYPE=DEBUG \ +# CROSS_COMPILE=arm-linux-androideabi- \ +# SRCDIRS="src/base src/event" \ +# INCDIRS="src/util" \ +# SRCS="src/util/hmain.cpp src/util/iniparser.cpp" \ +# DEFINES=USE_OPENCV \ +# LIBS="opencv_core opencv_highgui" +#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +-include config.mk + +# VARIABLES +TARGET ?= test +# BUILD_TYPE=DEBUG,RELEASE +BUILD_TYPE ?= RELEASE +# TARGET_TYPE=EXECUTABLE,SHARED,STATIC,SHARED|STATIC +TARGET_TYPE ?= EXECUTABLE + +# COMMANDS +ifdef CROSS_COMPILE +CC = $(CROSS_COMPILE)gcc +CXX = $(CROSS_COMPILE)g++ +CPP = $(CC) -E +AS = $(CROSS_COMPILE)as +LD = $(CROSS_COMPILE)ld +AR = $(CROSS_COMPILE)ar +NM = $(CROSS_COMPILE)nm +STRIP = $(CROSS_COMPILE)strip +endif + +MKDIR = -mkdir -p 2>/dev/null +CP = -cp -r 2>/dev/null +RM = -rm -r 2>/dev/null + +# PLATFORM: OS, ARCH +CC_VERSION=$(shell $(CC) --version 2>&1 | head -n 1) +TARGET_PLATFORM=$(shell $(CC) -v 2>&1 | grep Target | sed 's/Target: //') +ifneq ($(findstring mingw, $(TARGET_PLATFORM)), ) + OS=Windows +endif +ifneq ($(findstring android, $(TARGET_PLATFORM)), ) + OS=Android +endif +ifneq ($(findstring darwin, $(TARGET_PLATFORM)), ) + OS=Darwin +endif +ifndef OS + OS=Linux +endif + +ifndef ARCH +ARCH=$(shell echo $(TARGET_PLATFORM) | awk -F'-' '{print $$1}') +endif + +# CFLAGS, CXXFLAGS, ARFLAGS +ifeq ($(BUILD_TYPE), DEBUG) + DEFAULT_CFLAGS = -g -Wall -O0 +else + DEFAULT_CFLAGS += -O2 +endif + +CFLAGS ?= $(DEFAULT_CFLAGS) +CXXFLAGS ?= $(DEFAULT_CFLAGS) + +ifneq ($(OS), Windows) +ifeq ($(findstring -fPIC, $(CFLAGS)), ) +override CFLAGS += -fPIC +endif +ifeq ($(findstring -fPIC, $(CXXFLAGS)), ) +override CXXFLAGS += -fPIC +endif +endif + +ifeq ($(findstring -std, $(CFLAGS)), ) +override CFLAGS += -std=c99 +endif + +ifeq ($(findstring -std, $(CXXFLAGS)), ) +override CXXFLAGS += -std=c++11 +endif + +ARFLAGS ?= cr + +# DIRS +ifeq ($(OS), Linux) + PREFIX ?= /usr/local +else + PREFIX ?= install +endif + +INCDIR = include +LIBDIR = lib +SRCDIR = src +BINDIR = bin +DEPDIR = 3rd +CONFDIR = etc +DISTDIR = dist +DOCDIR = docs + +SRCDIRS += $(shell find $(SRCDIR) -type d) +override INCDIRS += $(INCDIR) $(DEPDIR) $(DEPDIR)/include +override LIBDIRS += $(LIBDIR) $(DEPDIR)/lib $(DEPDIR)/lib/$(TARGET_PLATFORM) + +ALL_SRCS += $(foreach dir, $(SRCDIRS), $(wildcard $(dir)/*.c $(dir)/*.cc $(dir)/*.cpp)) +ifeq ($(ALL_SRCS), ) + ALL_SRCS = $(wildcard *.c *.cc *.cpp) +endif +override SRCS += $(filter-out %_test.c %_test.cc %_test.cpp, $(ALL_SRCS)) +# OBJS += $(patsubst %.c, %.o, $(SRCS)) +# OBJS += $(patsubst %.cc, %.o, $(SRCS)) +# OBJS += $(patsubst %.cpp, %.o, $(SRCS)) +OBJS := $(addsuffix .o, $(basename $(SRCS))) + +INSTALLED_INCS=$(addprefix $(PREFIX)/$(INCDIR)/, $(shell ls $(INCDIR))) +INSTALLED_LIBS=$(addprefix $(PREFIX)/$(LIBDIR)/, $(shell ls $(LIBDIR))) +INSTALLED_BINS=$(addprefix $(PREFIX)/$(BINDIR)/, $(shell ls $(BINDIR))) + +# CPPFLAGS +ifeq ($(OS), Windows) + CPPFLAGS += -D_WIN32_WINNT=0x600 +ifeq ($(TARGET_TYPE), SHARED) + CPPFLAGS += -DDLL_EXPORTS +endif +endif + +ifeq ($(BUILD_TYPE), DEBUG) + CPPFLAGS += -DDEBUG +else + CPPFLAGS += -DNDEBUG +endif + +ifeq ($(ENABLE_UDS), yes) + CPPFLAGS += -DENABLE_UDS +endif + +ifeq ($(USE_MULTIMAP), yes) + CPPFLAGS += -DUSE_MULTIMAP +endif + +CPPFLAGS += $(addprefix -D, $(DEFINES)) +CPPFLAGS += $(addprefix -I, $(INCDIRS)) +CPPFLAGS += $(addprefix -I, $(SRCDIRS)) + +# LDFLAGS +ifeq ($(OS), Windows) + LDFLAGS += -static-libgcc -static-libstdc++ +endif + +ifeq ($(WITH_CURL), yes) + CPPFLAGS += -DWITH_CURL + LDFLAGS += -lcurl +ifeq ($(OS), Windows) + LDFLAGS += -lwldap32 -ladvapi32 -lcrypt32 +endif +endif + +ifeq ($(WITH_NGHTTP2), yes) + CPPFLAGS += -DWITH_NGHTTP2 + LDFLAGS += -lnghttp2 +endif + +ifeq ($(WITH_OPENSSL), yes) + CPPFLAGS += -DWITH_OPENSSL + LDFLAGS += -lssl -lcrypto +else +ifeq ($(WITH_GNUTLS), yes) + CPPFLAGS += -DWITH_GNUTLS + LDFLAGS += -lgnutls +else +ifeq ($(WITH_MBEDTLS), yes) + CPPFLAGS += -DWITH_MBEDTLS + LDFLAGS += -lmbedtls -lmbedx509 -lmbedcrypto +endif +endif +endif + +LDFLAGS += $(addprefix -L, $(LIBDIRS)) +LDFLAGS += $(addprefix -l, $(LIBS)) + +ifeq ($(OS), Windows) + LDFLAGS += -lsecur32 -lcrypt32 -lwinmm -liphlpapi -lws2_32 +ifeq ($(ENABLE_WINDUMP), yes) + CPPFLAGS += -DENABLE_WINDUMP + LDFLAGS += -ldbghelp +endif + LDFLAGS += -Wl,-Bstatic -lstdc++ -lpthread -lm +else +ifeq ($(filter %.cc %.cpp, $(SRCS)), ) + LINK = $(CC) +else + LINK = $(CXX) + LDFLAGS += -lstdc++ +endif +ifeq ($(OS), Android) + LDFLAGS += -lm -llog -ldl +else + LDFLAGS += -lpthread -lm -ldl + LINK_RT=$(shell echo "int main(){return 0;}" | $(CC) -x c - -lrt 2>&1) +ifeq ($(LINK_RT), ) + LDFLAGS += -lrt +endif +endif +endif + +ifeq ($(OS), Darwin) + LDFLAGS += -framework CoreFoundation -framework Security +endif + +LINK ?= $(CC) + +# info +$(info $(CC_VERSION)) + +$(info OS = $(OS)) +$(info ARCH = $(ARCH)) +$(info MAKE = $(MAKE)) +$(info CC = $(CC)) +$(info CXX = $(CXX)) + +$(info CFLAGS = $(CFLAGS)) +$(info CXXFLAGS = $(CXXFLAGS)) +$(info CPPFLAGS = $(CPPFLAGS)) +$(info LDFLAGS = $(LDFLAGS)) + +$(info TARGET = $(TARGET)) +$(info TARGET_TYPE = $(TARGET_TYPE)) +$(info TARGET_PLATFORM = $(TARGET_PLATFORM)) +$(info BUILD_TYPE = $(BUILD_TYPE)) + +$(info SRCS=$(SRCS)) +$(info OBJS=$(OBJS)) + +# $(info INSTALLED_INCS=$(INSTALLED_INCS)) +# $(info INSTALLED_LIBS=$(INSTALLED_LIBS)) +# $(info INSTALLED_BINS=$(INSTALLED_BINS)) + +default: all + +all: prepare $(TARGET) + +prepare: + $(MKDIR) $(BINDIR) $(LIBDIR) + +$(TARGET): $(OBJS) +ifneq ($(findstring SHARED, $(TARGET_TYPE)), ) +ifeq ($(OS), Windows) + $(LINK) -shared $^ -o $(LIBDIR)/$@.dll $(LDFLAGS) -Wl,--output-def,$(LIBDIR)/$(@).def +else +ifeq ($(OS), Darwin) + $(LINK) -dynamiclib -install_name @rpath/$@.dylib $^ -o $(LIBDIR)/$@.dylib $(LDFLAGS) +else + $(LINK) -shared $^ -o $(LIBDIR)/$@.so $(LDFLAGS) +endif +endif +endif + +ifneq ($(findstring STATIC, $(TARGET_TYPE)), ) + $(AR) $(ARFLAGS) $(LIBDIR)/$@.a $^ +endif + +ifneq ($(findstring EXECUTABLE, $(TARGET_TYPE)), ) +ifeq ($(OS), Windows) + $(LINK) $^ -o $(BINDIR)/$@.exe $(LDFLAGS) +else + $(LINK) $^ -o $(BINDIR)/$@ $(LDFLAGS) +endif +endif + +clean: + $(RM) $(OBJS) + #$(RM) $(LIBDIR) + #$(RM) $(BINDIR) + +install: + $(CP) $(INCDIR)/* $(PREFIX)/$(INCDIR)/ + $(CP) $(LIBDIR)/* $(PREFIX)/$(LIBDIR)/ + $(CP) $(BINDIR)/* $(PREFIX)/$(BINDIR)/ + $(LDCONFIG) + +uninstall: + $(RM) $(INSTALLED_INCS) + $(RM) $(INSTALLED_LIBS) + $(RM) $(INSTALLED_BINS) + +dist: + $(MKDIR) $(DISTDIR) + $(CP) $(INCDIR) $(LIBDIR) $(BINDIR) $(CONFDIR) $(DOCDIR) $(DISTDIR) + +undist: + $(RM) $(DISTDIR) + +.PHONY: default all prepare clean install uninstall dist undist diff --git a/external/libhv/libhv-1.3.2/Makefile.vars b/external/libhv/libhv-1.3.2/Makefile.vars new file mode 100644 index 0000000..8f091c6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/Makefile.vars @@ -0,0 +1,95 @@ +MKDIR = -mkdir -p 2>/dev/null +CP = -cp -r 2>/dev/null +RM = -rm -r 2>/dev/null +LDCONFIG = -ldconfig 2>/dev/null + +PREFIX ?= /usr/local +INSTALL_INCDIR ?= $(PREFIX)/include/hv +INSTALL_LIBDIR ?= $(PREFIX)/lib + +BASE_HEADERS = base/hplatform.h\ + \ + base/hdef.h\ + base/hatomic.h\ + base/herr.h\ + base/htime.h\ + base/hmath.h\ + base/hbase.h\ + base/hversion.h\ + base/hsysinfo.h\ + base/hproc.h\ + base/hthread.h\ + base/hmutex.h\ + base/hsocket.h\ + base/hlog.h\ + base/hbuf.h\ + base/hmain.h\ + base/hendian.h\ + +SSL_HEADERS = ssl/hssl.h + +EVENT_HEADERS = event/hloop.h\ + event/nlog.h\ + +UTIL_HEADERS = util/base64.h\ + util/md5.h\ + util/sha1.h\ + +CPPUTIL_HEADERS = cpputil/hmap.h\ + cpputil/hstring.h\ + cpputil/hfile.h\ + cpputil/hpath.h\ + cpputil/hdir.h\ + cpputil/hurl.h\ + cpputil/hscope.h\ + cpputil/hthreadpool.h\ + cpputil/hasync.h\ + cpputil/hobjectpool.h\ + cpputil/ifconfig.h\ + cpputil/iniparser.h\ + cpputil/json.hpp\ + cpputil/singleton.h\ + cpputil/ThreadLocalStorage.h\ + +EVPP_HEADERS = evpp/Buffer.h\ + evpp/Channel.h\ + evpp/Event.h\ + evpp/EventLoop.h\ + evpp/EventLoopThread.h\ + evpp/EventLoopThreadPool.h\ + evpp/Status.h\ + evpp/TcpClient.h\ + evpp/TcpServer.h\ + evpp/UdpClient.h\ + evpp/UdpServer.h\ + +PROTOCOL_HEADERS = protocol/icmp.h\ + protocol/dns.h\ + protocol/ftp.h\ + protocol/smtp.h + +HTTP_HEADERS = http/httpdef.h\ + http/wsdef.h\ + http/http_content.h\ + http/HttpMessage.h\ + http/HttpParser.h\ + http/WebSocketParser.h\ + http/WebSocketChannel.h\ + +HTTP2_HEADERS = http/http2def.h\ + http/grpcdef.h\ + +HTTP_CLIENT_HEADERS = http/client/HttpClient.h\ + http/client/requests.h\ + http/client/axios.h\ + http/client/AsyncHttpClient.h\ + http/client/WebSocketClient.h\ + +HTTP_SERVER_HEADERS = http/server/HttpServer.h\ + http/server/HttpService.h\ + http/server/HttpContext.h\ + http/server/HttpResponseWriter.h\ + http/server/WebSocketServer.h\ + +MQTT_HEADERS = mqtt/mqtt_protocol.h\ + mqtt/mqtt_client.h\ diff --git a/external/libhv/libhv-1.3.2/README-CN.md b/external/libhv/libhv-1.3.2/README-CN.md new file mode 100644 index 0000000..74953eb --- /dev/null +++ b/external/libhv/libhv-1.3.2/README-CN.md @@ -0,0 +1,537 @@ +[English](README.md) | 中文 + +# libhv + +[![Linux](https://badgen.net/badge/Linux/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![Windows](https://badgen.net/badge/Windows/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![macOS](https://badgen.net/badge/macOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![Android](https://badgen.net/badge/Android/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![iOS](https://badgen.net/badge/iOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![benchmark](https://github.com/ithewei/libhv/workflows/benchmark/badge.svg?branch=master)](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml?query=branch%3Amaster) +
+[![release](https://badgen.net/github/release/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/releases) +[![stars](https://badgen.net/github/stars/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/stargazers) +[![forks](https://badgen.net/github/forks/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/forks) +[![issues](https://badgen.net/github/issues/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/issues) +[![PRs](https://badgen.net/github/prs/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/pulls) +[![contributors](https://badgen.net/github/contributors/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/contributors) +[![license](https://badgen.net/github/license/ithewei/libhv?icon=github)](LICENSE) +
+[![gitee](https://badgen.net/badge/mirror/gitee/red)](https://gitee.com/libhv/libhv) +[![awesome-c](https://badgen.net/badge/icon/awesome-c/pink?icon=awesome&label&color)](https://github.com/oz123/awesome-c) +[![awesome-cpp](https://badgen.net/badge/icon/awesome-cpp/pink?icon=awesome&label&color)](https://github.com/fffaraz/awesome-cpp) + +`libhv`是一个类似于`libevent、libev、libuv`的跨平台网络库,提供了更易用的接口和更丰富的协议。 + +## 📚 中文资料 + +- **libhv QQ群**: `739352073`,欢迎加群交流 +- **libhv 源码剖析**: +- **libhv 接口手册**: +- **libhv 教程目录**: +- [libhv教程01--介绍与体验](https://hewei.blog.csdn.net/article/details/113702536) +- [libhv教程02--编译与安装](https://hewei.blog.csdn.net/article/details/113704737) +- [libhv教程03--链库与使用](https://hewei.blog.csdn.net/article/details/113706378) +- [libhv教程04--编写一个完整的命令行程序](https://hewei.blog.csdn.net/article/details/113719503) +- [libhv教程05--事件循环以及定时器的简单使用](https://hewei.blog.csdn.net/article/details/113724474) +- [libhv教程06--创建一个简单的TCP服务端](https://hewei.blog.csdn.net/article/details/113737580) +- [libhv教程07--创建一个简单的TCP客户端](https://hewei.blog.csdn.net/article/details/113738900) +- [libhv教程08--创建一个简单的UDP服务端](https://hewei.blog.csdn.net/article/details/113871498) +- [libhv教程09--创建一个简单的UDP客户端](https://hewei.blog.csdn.net/article/details/113871724) +- [libhv教程10--创建一个简单的HTTP服务端](https://hewei.blog.csdn.net/article/details/113982999) +- [libhv教程11--创建一个简单的HTTP客户端](https://hewei.blog.csdn.net/article/details/113984302) +- [libhv教程12--创建一个简单的WebSocket服务端](https://hewei.blog.csdn.net/article/details/113985321) +- [libhv教程13--创建一个简单的WebSocket客户端](https://hewei.blog.csdn.net/article/details/113985895) +- [libhv教程14--200行实现一个纯C版jsonrpc框架](https://hewei.blog.csdn.net/article/details/119920540) +- [libhv教程15--200行实现一个C++版protorpc框架](https://hewei.blog.csdn.net/article/details/119966701) +- [libhv教程16--多线程/多进程服务端编程](https://hewei.blog.csdn.net/article/details/120366024) +- [libhv教程17--Qt中使用libhv](https://hewei.blog.csdn.net/article/details/120699890) +- [libhv教程18--动手写一个tinyhttpd](https://hewei.blog.csdn.net/article/details/121706604) +- [libhv教程19--MQTT的实现与使用](https://hewei.blog.csdn.net/article/details/122753665) + +## ✨ 特性 + +- 跨平台(Linux, Windows, macOS, Android, iOS, BSD, Solaris) +- 高性能事件循环(网络IO事件、定时器事件、空闲事件、自定义事件) +- TCP/UDP服务端/客户端/代理 +- TCP支持心跳、重连、转发、多线程安全write和close等特性 +- 内置常见的拆包模式(固定包长、分界符、头部长度字段) +- 可靠UDP支持: WITH_KCP +- SSL/TLS加密通信(可选WITH_OPENSSL、WITH_GNUTLS、WITH_MBEDTLS) +- HTTP服务端/客户端(支持https http1/x http2 grpc) +- HTTP支持静态文件服务、目录服务、正向/反向代理服务、同步/异步API处理器 +- HTTP支持RESTful风格、路由、中间件、keep-alive长连接、chunked分块、SSE等特性 +- WebSocket服务端/客户端 +- MQTT客户端 + +## ⌛️ 构建 + +见[BUILD.md](BUILD.md) + +libhv提供了以下构建方式: + +1、通过Makefile: +```shell +./configure +make +sudo make install +``` + +2、通过cmake: +```shell +mkdir build +cd build +cmake .. +cmake --build . +``` + +3、通过vcpkg: +```shell +vcpkg install libhv +``` + +4、通过xmake: +```shell +xrepo install libhv +``` + +## ⚡️ 快速入门 + +### 体验 +运行脚本`./getting_started.sh`: + +```shell +# 下载编译 +git clone https://github.com/ithewei/libhv.git +cd libhv +./configure +make + +# 运行httpd服务 +bin/httpd -h +bin/httpd -d +#bin/httpd -c etc/httpd.conf -s restart -d +ps aux | grep httpd + +# 文件服务 +bin/curl -v localhost:8080 + +# 目录服务 +bin/curl -v localhost:8080/downloads/ + +# API服务 +bin/curl -v localhost:8080/ping +bin/curl -v localhost:8080/echo -d "hello,world!" +bin/curl -v localhost:8080/query?page_no=1\&page_size=10 +bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' +bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' +bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' +bin/curl -v localhost:8080/upload -d "@LICENSE" +bin/curl -v localhost:8080/upload -F "file=@LICENSE" + +bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' +bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' +bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' +# RESTful API: /group/:group_name/user/:user_id +bin/curl -v -X DELETE localhost:8080/group/test/user/123 + +# 压力测试 +bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ +``` + +### TCP +#### TCP服务端 +**c版本**: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) + +**c++版本**: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) +```c++ +#include "TcpServer.h" +using namespace hv; + +int main() { + int port = 1234; + TcpServer srv; + int listenfd = srv.createsocket(port); + if (listenfd < 0) { + return -1; + } + printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); + srv.onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + // echo + channel->write(buf); + }; + srv.setThreadNum(4); + srv.start(); + + // press Enter to stop + while (getchar() != '\n'); + return 0; +} +``` + +**注意**: + +以上示例只是简单的`echo`服务,TCP是流式协议,实际应用中请务必添加边界进行拆包。
+文本协议建议加上`\0`或者`\r\n`分隔符,可参考 [examples/jsonrpc](examples/jsonrpc);
+二进制协议建议加上自定义协议头,通过头部长度字段表明负载长度,可参考 [examples/protorpc](examples/protorpc);
+通过`setUnpack`(c接口即`hio_set_unpack`)设置拆包规则,支持固定包长、分隔符、头部长度字段三种常见的拆包方式,
+内部根据拆包规则处理粘包与分包,保证`onMessage`回调上来的是完整的一包数据,大大节省了上层处理粘包与分包的成本。
+不想自定义协议和拆包组包的可直接使用现成的`HTTP/WebSocket`协议。
+
+`channel->write`(c接口即`hio_write`)是非阻塞的(事件循环异步编程里所有的一切都要求是非阻塞的),且多线程安全的。
+发送大数据时应该做流控,通过`onWriteComplete`监听写完成事件,在可写时再发送下一帧数据。
+具体示例代码可参考 [examples/tinyhttpd.c](examples/tinyhttpd.c) 中的 `http_serve_file`。
+
+`channel->close`(c接口即`hio_close`) 也是多线程安全的,这可以让网络IO事件循环线程里接收数据、拆包组包、反序列化后放入队列,
+消费者线程/线程池从队列里取出数据、处理后发送响应和关闭连接,变得更加简单。
+ +#### TCP客户端 +**c版本**: [examples/tcp_client_test.c](examples/tcp_client_test.c) + +**c++版本**: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) +```c++ +#include +#include "TcpClient.h" +using namespace hv; + +int main() { + int port = 1234; + TcpClient cli; + int connfd = cli.createsocket(port); + if (connfd < 0) { + return -1; + } + cli.onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + }; + cli.start(); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + cli.closesocket(); + } else if (str == "start") { + cli.start(); + } else if (str == "stop") { + cli.stop(); + break; + } else { + if (!cli.isConnected()) break; + cli.send(str); + } + } + return 0; +} +``` + +### HTTP +#### HTTP服务端 +见[examples/http_server_test.cpp](examples/http_server_test.cpp) + +**golang gin 风格** +```c++ +#include "HttpServer.h" +using namespace hv; + +int main() { + HttpService router; + router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { + return resp->String("pong"); + }); + + router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { + static char data[] = "0123456789"; + return resp->Data(data, 10); + }); + + router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { + return resp->Json(router.Paths()); + }); + + router.GET("/get", [](HttpRequest* req, HttpResponse* resp) { + resp->json["origin"] = req->client_addr.ip; + resp->json["url"] = req->url; + resp->json["args"] = req->query_params; + resp->json["headers"] = req->headers; + return 200; + }); + + router.POST("/echo", [](const HttpContextPtr& ctx) { + return ctx->send(ctx->body(), ctx->type()); + }); + + HttpServer server(&router); + server.setPort(8080); + server.setThreadNum(4); + server.run(); + return 0; +} +``` + +**注意**: + +上面示例直接运行在`main`主线程,`server.run()`会阻塞当前线程运行,所以`router`和`server`对象不会被析构,
+如使用`server.start()`内部会另起线程运行,不会阻塞当前线程,但需要注意`router`和`server`的生命周期,
+不要定义为局部变量被析构了,可定义为类成员变量或者全局变量,下面的`WebSocket`服务同理。
+ +#### HTTP客户端 +见[examples/http_client_test.cpp](examples/http_client_test.cpp) + +**python requests 风格** +```c++ +#include "requests.h" + +int main() { + auto resp = requests::get("http://www.example.com"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + + resp = requests::post("127.0.0.1:8080/echo", "hello,world!"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + + return 0; +} +``` + +附HTTP相关接口文档: + +- [class HttpMessage](docs/cn/HttpMessage.md) +- [class HttpClient](docs/cn/HttpClient.md) +- [class HttpServer](docs/cn/HttpServer.md) +- [class HttpContext](docs/cn/HttpContext.md) + +### WebSocket +#### WebSocket服务端 +见[examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) +```c++ +#include "WebSocketServer.h" +using namespace hv; + +int main(int argc, char** argv) { + WebSocketService ws; + ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { + printf("onopen: GET %s\n", req->Path().c_str()); + }; + ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { + printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); + }; + ws.onclose = [](const WebSocketChannelPtr& channel) { + printf("onclose\n"); + }; + + WebSocketServer server(&ws); + server.setPort(9999); + server.setThreadNum(4); + server.run(); + return 0; +} +``` + +#### WebSocket客户端 +见[examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) +```c++ +#include "WebSocketClient.h" +using namespace hv; + +int main(int argc, char** argv) { + WebSocketClient ws; + ws.onopen = []() { + printf("onopen\n"); + }; + ws.onmessage = [](const std::string& msg) { + printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); + }; + ws.onclose = []() { + printf("onclose\n"); + }; + + // reconnect: 1,2,4,8,10,10,10... + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + ws.setReconnect(&reconn); + + ws.open("ws://127.0.0.1:9999/test"); + + std::string str; + while (std::getline(std::cin, str)) { + if (!ws.isConnected()) break; + if (str == "quit") { + ws.close(); + break; + } + ws.send(str); + } + + return 0; +} +``` + +## 🍭 更多示例 + +### c版本 +- 事件循环: [examples/hloop_test.c](examples/hloop_test.c) +- 定时器: [examples/htimer_test.c](examples/htimer_test.c) +- TCP回显服务: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) +- TCP聊天服务: [examples/tcp_chat_server.c](examples/tcp_chat_server.c) +- TCP代理服务: [examples/tcp_proxy_server.c](examples/tcp_proxy_server.c) +- UDP回显服务: [examples/udp_echo_server.c](examples/udp_echo_server.c) +- UDP代理服务: [examples/udp_proxy_server.c](examples/udp_proxy_server.c) +- SOCKS5代理服务: [examples/socks5_proxy_server.c](examples/socks5_proxy_server.c) +- HTTP服务: [examples/tinyhttpd.c](examples/tinyhttpd.c) +- HTTP代理服务: [examples/tinyproxyd.c](examples/tinyproxyd.c) +- jsonRPC示例: [examples/jsonrpc](examples/jsonrpc) +- MQTT示例: [examples/mqtt](examples/mqtt) +- 多accept进程模式: [examples/multi-thread/multi-acceptor-processes.c](examples/multi-thread/multi-acceptor-processes.c) +- 多accept线程模式: [examples/multi-thread/multi-acceptor-threads.c](examples/multi-thread/multi-acceptor-threads.c) +- 一个accept线程+多worker线程: [examples/multi-thread/one-acceptor-multi-workers.c](examples/multi-thread/one-acceptor-multi-workers.c) + +### c++版本 +- 事件循环: [evpp/EventLoop_test.cpp](evpp/EventLoop_test.cpp) +- 事件循环线程: [evpp/EventLoopThread_test.cpp](evpp/EventLoopThread_test.cpp) +- 事件循环线程池: [evpp/EventLoopThreadPool_test.cpp](evpp/EventLoopThreadPool_test.cpp) +- 定时器: [evpp/TimerThread_test.cpp](evpp/TimerThread_test.cpp) +- TCP服务端: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) +- TCP客户端: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) +- UDP服务端: [evpp/UdpServer_test.cpp](evpp/UdpServer_test.cpp) +- UDP客户端: [evpp/UdpClient_test.cpp](evpp/UdpClient_test.cpp) +- HTTP服务端: [examples/http_server_test.cpp](examples/http_server_test.cpp) +- HTTP客户端: [examples/http_client_test.cpp](examples/http_client_test.cpp) +- WebSocket服务端: [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) +- WebSocket客户端: [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) +- protobufRPC示例: [examples/protorpc](examples/protorpc) +- Qt中使用libhv示例: [hv-projects/QtDemo](https://github.com/hv-projects/QtDemo) + +### 模拟实现著名的命令行工具 +- 网络连接工具: [examples/nc](examples/nc.c) +- 网络扫描工具: [examples/nmap](examples/nmap) +- HTTP服务程序: [examples/httpd](examples/httpd) +- HTTP压测工具: [examples/wrk](examples/wrk.cpp) +- URL请求工具: [examples/curl](examples/curl.cpp) +- 文件下载工具: [examples/wget](examples/wget.cpp) +- 服务注册与发现: [examples/consul](examples/consul) + +## 🥇 性能测试 + +### TCP回显服务pingpong测试 +```shell +cd echo-servers +./build.sh +./benchmark.sh +``` + +**吞吐量**: +```shell +libevent running on port 2001 +libev running on port 2002 +libuv running on port 2003 +libhv running on port 2004 +asio running on port 2005 +poco running on port 2006 + +==============2001===================================== +[127.0.0.1:2001] 4 threads 1000 connections run 10s +total readcount=1616761 readbytes=1655563264 +throughput = 157 MB/s + +==============2002===================================== +[127.0.0.1:2002] 4 threads 1000 connections run 10s +total readcount=2153171 readbytes=2204847104 +throughput = 210 MB/s + +==============2003===================================== +[127.0.0.1:2003] 4 threads 1000 connections run 10s +total readcount=1599727 readbytes=1638120448 +throughput = 156 MB/s + +==============2004===================================== +[127.0.0.1:2004] 4 threads 1000 connections run 10s +total readcount=2202271 readbytes=2255125504 +throughput = 215 MB/s + +==============2005===================================== +[127.0.0.1:2005] 4 threads 1000 connections run 10s +total readcount=1354230 readbytes=1386731520 +throughput = 132 MB/s + +==============2006===================================== +[127.0.0.1:2006] 4 threads 1000 connections run 10s +total readcount=1699652 readbytes=1740443648 +throughput = 165 MB/s +``` + +### TCP代理服务压测 + +```shell +# sudo apt install iperf +iperf -s -p 5001 > /dev/null & +bin/tcp_proxy_server 1212 127.0.0.1:5001 & +iperf -c 127.0.0.1 -p 5001 -l 8K +iperf -c 127.0.0.1 -p 1212 -l 8K +``` + +**带宽**: +```shell +------------------------------------------------------------ +[ 3] local 127.0.0.1 port 52560 connected with 127.0.0.1 port 5001 +[ ID] Interval Transfer Bandwidth +[ 3] 0.0-10.0 sec 20.8 GBytes 17.9 Gbits/sec + +------------------------------------------------------------ +[ 3] local 127.0.0.1 port 48142 connected with 127.0.0.1 port 1212 +[ ID] Interval Transfer Bandwidth +[ 3] 0.0-10.0 sec 11.9 GBytes 10.2 Gbits/sec +``` + +### HTTP压测 +```shell +# sudo apt install wrk +wrk -c 100 -t 4 -d 10s http://127.0.0.1:8080/ + +# sudo apt install apache2-utils +ab -c 100 -n 100000 http://127.0.0.1:8080/ +``` + +**libhv(port:8080) vs nginx(port:80)** + +![libhv-vs-nginx.png](html/downloads/libhv-vs-nginx.png) + +以上测试结果可以在 [Github Actions](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml) 中查看。 + +## 💎 用户案例 + +如果您在使用`libhv`,欢迎通过PR将信息提交至此列表,让更多的用户了解`libhv`的实际使用场景,以建立更好的网络生态。 + +| 用户 (公司名/项目名/个人联系方式) | 案例 (项目简介/业务场景) | +| :--- | :--- | +| [阅面科技](https://www.readsense.cn) | [猎户AIoT平台](https://orionweb.readsense.cn)设备管理、人脸检测HTTP服务、人脸搜索HTTP服务 | +| [socks5-libhv](https://gitee.com/billykang/socks5-libhv) | socks5代理 | +| [hvloop](https://github.com/xiispace/hvloop) | 类似[uvloop](https://github.com/MagicStack/uvloop)的python异步IO事件循环 | +| [tsproxyd-android](https://github.com/Haiwen-GitHub/tsproxyd-android) | 一个基于libhv实现的android端web代理服务 | +| [玄舟智维](https://zjzwxw.com) | C100K设备连接网关服务 | + diff --git a/external/libhv/libhv-1.3.2/README.md b/external/libhv/libhv-1.3.2/README.md new file mode 100644 index 0000000..8b0f8a5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/README.md @@ -0,0 +1,462 @@ +English | [中文](README-CN.md) + +# libhv + +[![Linux](https://badgen.net/badge/Linux/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![Windows](https://badgen.net/badge/Windows/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![macOS](https://badgen.net/badge/macOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![Android](https://badgen.net/badge/Android/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![iOS](https://badgen.net/badge/iOS/success/green?icon=github)](https://github.com/ithewei/libhv/actions/workflows/CI.yml?query=branch%3Amaster) +[![benchmark](https://github.com/ithewei/libhv/workflows/benchmark/badge.svg?branch=master)](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml?query=branch%3Amaster) +
+[![release](https://badgen.net/github/release/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/releases) +[![stars](https://badgen.net/github/stars/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/stargazers) +[![forks](https://badgen.net/github/forks/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/forks) +[![issues](https://badgen.net/github/issues/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/issues) +[![PRs](https://badgen.net/github/prs/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/pulls) +[![contributors](https://badgen.net/github/contributors/ithewei/libhv?icon=github)](https://github.com/ithewei/libhv/contributors) +[![license](https://badgen.net/github/license/ithewei/libhv?icon=github)](LICENSE) +
+[![gitee](https://badgen.net/badge/mirror/gitee/red)](https://gitee.com/libhv/libhv) +[![awesome-c](https://badgen.net/badge/icon/awesome-c/pink?icon=awesome&label&color)](https://github.com/oz123/awesome-c) +[![awesome-cpp](https://badgen.net/badge/icon/awesome-cpp/pink?icon=awesome&label&color)](https://github.com/fffaraz/awesome-cpp) + +Like `libevent, libev, and libuv`, +`libhv` provides event-loop with non-blocking IO and timer, +but simpler api and richer protocols. + +## ✨ Features + +- Cross-platform (Linux, Windows, macOS, Android, iOS, BSD, Solaris) +- High-performance EventLoop (IO, timer, idle, custom) +- TCP/UDP client/server/proxy +- TCP supports heartbeat, reconnect, upstream, MultiThread-safe write and close, etc. +- Built-in common unpacking modes (FixedLength, Delimiter, LengthField) +- RUDP support: WITH_KCP +- SSL/TLS support: (via WITH_OPENSSL or WITH_GNUTLS or WITH_MBEDTLS) +- HTTP client/server (support https http1/x http2 grpc) +- HTTP supports static service, indexof service, forward/reverse proxy service, sync/async API handler +- HTTP supports RESTful, router, middleware, keep-alive, chunked, SSE, etc. +- WebSocket client/server +- MQTT client + +## ⌛️ Build + +see [BUILD.md](BUILD.md) + +Makefile: +```shell +./configure +make +sudo make install +``` + +or cmake: +```shell +mkdir build +cd build +cmake .. +cmake --build . +``` + +or vcpkg: +```shell +vcpkg install libhv +``` + +or xmake: +```shell +xrepo install libhv +``` + +## ⚡️ Getting Started + +run `./getting_started.sh`: + +```shell +git clone https://github.com/ithewei/libhv.git +cd libhv +./configure +make + +bin/httpd -h +bin/httpd -d +#bin/httpd -c etc/httpd.conf -s restart -d +ps aux | grep httpd + +# http file service +bin/curl -v localhost:8080 + +# http indexof service +bin/curl -v localhost:8080/downloads/ + +# http api service +bin/curl -v localhost:8080/ping +bin/curl -v localhost:8080/echo -d "hello,world!" +bin/curl -v localhost:8080/query?page_no=1\&page_size=10 +bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' +bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' +bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' +bin/curl -v localhost:8080/upload -d "@LICENSE" +bin/curl -v localhost:8080/upload -F "file=@LICENSE" + +bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' +bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' +bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' +# RESTful API: /group/:group_name/user/:user_id +bin/curl -v -X DELETE localhost:8080/group/test/user/123 + +# benchmark +bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ +``` + +### TCP +#### tcp server +**c version**: [examples/tcp_echo_server.c](examples/tcp_echo_server.c) + +**c++ version**: [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) +```c++ +#include "TcpServer.h" +using namespace hv; + +int main() { + int port = 1234; + TcpServer srv; + int listenfd = srv.createsocket(port); + if (listenfd < 0) { + return -1; + } + printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); + srv.onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + // echo + channel->write(buf); + }; + srv.setThreadNum(4); + srv.start(); + + // press Enter to stop + while (getchar() != '\n'); + return 0; +} +``` + +#### tcp client +**c version**: [examples/tcp_client_test.c](examples/tcp_client_test.c) + +**c++ version**: [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) +```c++ +#include +#include "TcpClient.h" +using namespace hv; + +int main() { + int port = 1234; + TcpClient cli; + int connfd = cli.createsocket(port); + if (connfd < 0) { + return -1; + } + cli.onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + }; + cli.start(); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + cli.closesocket(); + } else if (str == "start") { + cli.start(); + } else if (str == "stop") { + cli.stop(); + break; + } else { + if (!cli.isConnected()) break; + cli.send(str); + } + } + return 0; +} +``` + +### HTTP +#### http server +see [examples/http_server_test.cpp](examples/http_server_test.cpp) + +**golang gin style** +```c++ +#include "HttpServer.h" +using namespace hv; + +int main() { + HttpService router; + router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { + return resp->String("pong"); + }); + + router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { + static char data[] = "0123456789"; + return resp->Data(data, 10); + }); + + router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { + return resp->Json(router.Paths()); + }); + + router.GET("/get", [](HttpRequest* req, HttpResponse* resp) { + resp->json["origin"] = req->client_addr.ip; + resp->json["url"] = req->url; + resp->json["args"] = req->query_params; + resp->json["headers"] = req->headers; + return 200; + }); + + router.POST("/echo", [](const HttpContextPtr& ctx) { + return ctx->send(ctx->body(), ctx->type()); + }); + + HttpServer server(&router); + server.setPort(8080); + server.setThreadNum(4); + server.run(); + return 0; +} +``` +#### http client +see [examples/http_client_test.cpp](examples/http_client_test.cpp) + +**python requests style** +```c++ +#include "requests.h" + +int main() { + auto resp = requests::get("http://www.example.com"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + + resp = requests::post("127.0.0.1:8080/echo", "hello,world!"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + + return 0; +} +``` + +### WebSocket +#### WebSocket server +see [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) +```c++ +#include "WebSocketServer.h" +using namespace hv; + +int main(int argc, char** argv) { + WebSocketService ws; + ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { + printf("onopen: GET %s\n", req->Path().c_str()); + }; + ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { + printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); + }; + ws.onclose = [](const WebSocketChannelPtr& channel) { + printf("onclose\n"); + }; + + WebSocketServer server(&ws); + server.setPort(9999); + server.setThreadNum(4); + server.run(); + return 0; +} +``` + +#### WebSocket client +see [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) +```c++ +#include "WebSocketClient.h" +using namespace hv; + +int main(int argc, char** argv) { + WebSocketClient ws; + ws.onopen = []() { + printf("onopen\n"); + }; + ws.onmessage = [](const std::string& msg) { + printf("onmessage: %.*s\n", (int)msg.size(), msg.data()); + }; + ws.onclose = []() { + printf("onclose\n"); + }; + + // reconnect: 1,2,4,8,10,10,10... + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + ws.setReconnect(&reconn); + + ws.open("ws://127.0.0.1:9999/test"); + + std::string str; + while (std::getline(std::cin, str)) { + if (!ws.isConnected()) break; + if (str == "quit") { + ws.close(); + break; + } + ws.send(str); + } + + return 0; +} +``` + +## 🍭 More examples +### c version +- [examples/hloop_test.c](examples/hloop_test.c) +- [examples/htimer_test.c](examples/htimer_test.c) +- [examples/tcp_echo_server.c](examples/tcp_echo_server.c) +- [examples/tcp_chat_server.c](examples/tcp_chat_server.c) +- [examples/tcp_proxy_server.c](examples/tcp_proxy_server.c) +- [examples/udp_echo_server.c](examples/udp_echo_server.c) +- [examples/udp_proxy_server.c](examples/udp_proxy_server.c) +- [examples/socks5_proxy_server.c](examples/socks5_proxy_server.c) +- [examples/tinyhttpd.c](examples/tinyhttpd.c) +- [examples/tinyproxyd.c](examples/tinyproxyd.c) +- [examples/jsonrpc](examples/jsonrpc) +- [examples/mqtt](examples/mqtt) +- [examples/multi-thread/multi-acceptor-processes.c](examples/multi-thread/multi-acceptor-processes.c) +- [examples/multi-thread/multi-acceptor-threads.c](examples/multi-thread/multi-acceptor-threads.c) +- [examples/multi-thread/one-acceptor-multi-workers.c](examples/multi-thread/one-acceptor-multi-workers.c) + +### c++ version +- [evpp/EventLoop_test.cpp](evpp/EventLoop_test.cpp) +- [evpp/EventLoopThread_test.cpp](evpp/EventLoopThread_test.cpp) +- [evpp/EventLoopThreadPool_test.cpp](evpp/EventLoopThreadPool_test.cpp) +- [evpp/TimerThread_test.cpp](evpp/TimerThread_test.cpp) +- [evpp/TcpServer_test.cpp](evpp/TcpServer_test.cpp) +- [evpp/TcpClient_test.cpp](evpp/TcpClient_test.cpp) +- [evpp/UdpServer_test.cpp](evpp/UdpServer_test.cpp) +- [evpp/UdpClient_test.cpp](evpp/UdpClient_test.cpp) +- [examples/http_server_test.cpp](examples/http_server_test.cpp) +- [examples/http_client_test.cpp](examples/http_client_test.cpp) +- [examples/websocket_server_test.cpp](examples/websocket_server_test.cpp) +- [examples/websocket_client_test.cpp](examples/websocket_client_test.cpp) +- [examples/protorpc](examples/protorpc) +- [hv-projects/QtDemo](https://github.com/hv-projects/QtDemo) + +### simulate well-known command line tools +- [examples/nc](examples/nc.c) +- [examples/nmap](examples/nmap) +- [examples/httpd](examples/httpd) +- [examples/wrk](examples/wrk.cpp) +- [examples/curl](examples/curl.cpp) +- [examples/wget](examples/wget.cpp) +- [examples/consul](examples/consul) + +## 🥇 Benchmark +### `pingpong echo-servers` +```shell +cd echo-servers +./build.sh +./benchmark.sh +``` + +**throughput**: +```shell +libevent running on port 2001 +libev running on port 2002 +libuv running on port 2003 +libhv running on port 2004 +asio running on port 2005 +poco running on port 2006 + +==============2001===================================== +[127.0.0.1:2001] 4 threads 1000 connections run 10s +total readcount=1616761 readbytes=1655563264 +throughput = 157 MB/s + +==============2002===================================== +[127.0.0.1:2002] 4 threads 1000 connections run 10s +total readcount=2153171 readbytes=2204847104 +throughput = 210 MB/s + +==============2003===================================== +[127.0.0.1:2003] 4 threads 1000 connections run 10s +total readcount=1599727 readbytes=1638120448 +throughput = 156 MB/s + +==============2004===================================== +[127.0.0.1:2004] 4 threads 1000 connections run 10s +total readcount=2202271 readbytes=2255125504 +throughput = 215 MB/s + +==============2005===================================== +[127.0.0.1:2005] 4 threads 1000 connections run 10s +total readcount=1354230 readbytes=1386731520 +throughput = 132 MB/s + +==============2006===================================== +[127.0.0.1:2006] 4 threads 1000 connections run 10s +total readcount=1699652 readbytes=1740443648 +throughput = 165 MB/s +``` + +### `iperf tcp_proxy_server` +```shell +# sudo apt install iperf +iperf -s -p 5001 > /dev/null & +bin/tcp_proxy_server 1212 127.0.0.1:5001 & +iperf -c 127.0.0.1 -p 5001 -l 8K +iperf -c 127.0.0.1 -p 1212 -l 8K +``` + +**Bandwidth**: +```shell +------------------------------------------------------------ +[ 3] local 127.0.0.1 port 52560 connected with 127.0.0.1 port 5001 +[ ID] Interval Transfer Bandwidth +[ 3] 0.0-10.0 sec 20.8 GBytes 17.9 Gbits/sec + +------------------------------------------------------------ +[ 3] local 127.0.0.1 port 48142 connected with 127.0.0.1 port 1212 +[ ID] Interval Transfer Bandwidth +[ 3] 0.0-10.0 sec 11.9 GBytes 10.2 Gbits/sec +``` + +### `webbench` +```shell +# sudo apt install wrk +wrk -c 100 -t 4 -d 10s http://127.0.0.1:8080/ + +# sudo apt install apache2-utils +ab -c 100 -n 100000 http://127.0.0.1:8080/ +``` + +**libhv(port:8080) vs nginx(port:80)** + +![libhv-vs-nginx.png](html/downloads/libhv-vs-nginx.png) + +Above test results can be found on [Github Actions](https://github.com/ithewei/libhv/actions/workflows/benchmark.yml). diff --git a/external/libhv/libhv-1.3.2/TREE.md b/external/libhv/libhv-1.3.2/TREE.md new file mode 100644 index 0000000..f5a54a4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/TREE.md @@ -0,0 +1,36 @@ +## 目录结构 + +``` +. +├── base libhv基础设施,如常用宏定义、数据结构、日期时间、线程、进程、日志、套接字 +├── bin 可执行文件安装目录 +├── build cmake默认构建目录 +├── cert SSL证书存放目录 +├── cmake cmake脚本存放目录 +├── cpputil libhv工具类,如字符串、文件、路径、线程池、json解析、ini解析 +├── docs 文档存放目录 +├── echo-servers 包含libevent、libev、libuv、libhv、asio、poco、muduo等多个网络库的tcp echo server写法,并做压力测试 +├── etc 应用程序配置目录 +├── event libhv事件循环模块 +├── evpp 事件循环c++封装类 +├── examples 示例代码 +│   └── httpd +├── html 网页document_root目录 +│   ├── downloads 下载目录 +│   └── uploads 上传目录 +├── http libhv http模块 +│   ├── client +│   └── server +├── include 头文件安装目录 +│   └── hv +├── lib 库文件安装目录 +├── logs 日志生成目录 +├── misc 杂项 +├── mqtt MQTT协议 +├── protocol 包含icmp、dns、ftp、smtp等协议的实现 +├── scripts shell脚本存放目录 +├── ssl SSL/TLS加密通信 +├── unittest 单元测试代码 +└── util libhv工具函数,如base64、md5、sha1 + +``` diff --git a/external/libhv/libhv-1.3.2/base/README.md b/external/libhv/libhv-1.3.2/base/README.md new file mode 100644 index 0000000..399dc50 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/README.md @@ -0,0 +1,28 @@ +## 目录结构 + +``` +. +├── array.h 动态数组 +├── hatomic.h 原子操作 +├── hbase.h 基础函数 +├── hbuf.h 缓存 +├── hdef.h 常见宏定义 +├── heap.h 堆 +├── hendian.h 大小端 +├── herr.h 错误码表 +├── hlog.h 日志 +├── hmain.h 命令行解析 +├── hmath.h 数学函数 +├── hmutex.h 线程同步锁 +├── hplatform.h 平台相关宏 +├── hproc.h 进程 +├── hsocket.h 套接字 +├── hsysinfo.h 系统信息 +├── hthread.h 线程 +├── htime.h 时间 +├── hversion.h 版本 +├── list.h 链表 +├── queue.h 队列 +└── rbtree.h 红黑树 + +``` diff --git a/external/libhv/libhv-1.3.2/base/array.h b/external/libhv/libhv-1.3.2/base/array.h new file mode 100644 index 0000000..4370d5b --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/array.h @@ -0,0 +1,152 @@ +#ifndef HV_ARRAY_H_ +#define HV_ARRAY_H_ + +/* + * array + * at: random access by pos + * @effective + * push_back,pop_back,del_nomove,swap + * @ineffective + * add,del + */ + +#include // for assert +#include // for NULL +#include // for malloc,realloc,free +#include // for memset,memmove + +#include "hbase.h" // for HV_ALLOC, HV_FREE + +#define ARRAY_INIT_SIZE 16 + +// #include +// typedef std::vector atype; +#define ARRAY_DECL(type, atype) \ +struct atype { \ + type* ptr; \ + size_t size; \ + size_t maxsize;\ +}; \ +typedef struct atype atype;\ +\ +static inline type* atype##_data(atype* p) {\ + return p->ptr;\ +}\ +\ +static inline int atype##_size(atype* p) {\ + return p->size;\ +}\ +\ +static inline int atype##_maxsize(atype* p) {\ + return p->maxsize;\ +}\ +\ +static inline int atype##_empty(atype* p) {\ + return p->size == 0;\ +}\ +\ +static inline type* atype##_at(atype* p, int pos) {\ + if (pos < 0) {\ + pos += p->size;\ + }\ + assert(pos >= 0 && pos < p->size);\ + return p->ptr + pos;\ +}\ +\ +static inline type* atype##_front(atype* p) {\ + return p->size == 0 ? NULL : p->ptr;\ +}\ +\ +static inline type* atype##_back(atype* p) {\ + return p->size == 0 ? NULL : p->ptr + p->size - 1;\ +}\ +\ +static inline void atype##_init(atype* p, int maxsize) {\ + p->size = 0;\ + p->maxsize = maxsize;\ + HV_ALLOC(p->ptr, sizeof(type) * maxsize);\ +}\ +\ +static inline void atype##_clear(atype* p) {\ + p->size = 0;\ + memset(p->ptr, 0, sizeof(type) * p->maxsize);\ +}\ +\ +static inline void atype##_cleanup(atype* p) {\ + HV_FREE(p->ptr);\ + p->size = p->maxsize = 0;\ +}\ +\ +static inline void atype##_resize(atype* p, int maxsize) {\ + if (maxsize == 0) maxsize = ARRAY_INIT_SIZE;\ + p->ptr = (type*)hv_realloc(p->ptr, sizeof(type) * maxsize, sizeof(type) * p->maxsize);\ + p->maxsize = maxsize;\ +}\ +\ +static inline void atype##_double_resize(atype* p) {\ + atype##_resize(p, p->maxsize * 2);\ +}\ +\ +static inline void atype##_push_back(atype* p, type* elem) {\ + if (p->size == p->maxsize) {\ + atype##_double_resize(p);\ + }\ + p->ptr[p->size] = *elem;\ + p->size++;\ +}\ +\ +static inline void atype##_pop_back(atype* p) {\ + assert(p->size > 0);\ + p->size--;\ +}\ +\ +static inline void atype##_add(atype* p, type* elem, int pos) {\ + if (pos < 0) {\ + pos += p->size;\ + }\ + assert(pos >= 0 && pos <= p->size);\ + if (p->size == p->maxsize) {\ + atype##_double_resize(p);\ + }\ + if (pos < p->size) {\ + memmove(p->ptr + pos+1, p->ptr + pos, sizeof(type) * (p->size - pos));\ + }\ + p->ptr[pos] = *elem;\ + p->size++;\ +}\ +\ +static inline void atype##_del(atype* p, int pos) {\ + if (pos < 0) {\ + pos += p->size;\ + }\ + assert(pos >= 0 && pos < p->size);\ + p->size--;\ + if (pos < p->size) {\ + memmove(p->ptr + pos, p->ptr + pos+1, sizeof(type) * (p->size - pos));\ + }\ +}\ +\ +static inline void atype##_del_nomove(atype* p, int pos) {\ + if (pos < 0) {\ + pos += p->size;\ + }\ + assert(pos >= 0 && pos < p->size);\ + p->size--;\ + if (pos < p->size) {\ + p->ptr[pos] = p->ptr[p->size];\ + }\ +}\ +\ +static inline void atype##_swap(atype* p, int pos1, int pos2) {\ + if (pos1 < 0) {\ + pos1 += p->size;\ + }\ + if (pos2 < 0) {\ + pos2 += p->size;\ + }\ + type tmp = p->ptr[pos1];\ + p->ptr[pos1] = p->ptr[pos2];\ + p->ptr[pos2] = tmp;\ +}\ + +#endif // HV_ARRAY_H_ diff --git a/external/libhv/libhv-1.3.2/base/hatomic.h b/external/libhv/libhv-1.3.2/base/hatomic.h new file mode 100644 index 0000000..eea6a61 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hatomic.h @@ -0,0 +1,130 @@ +#ifndef HV_ATOMIC_H_ +#define HV_ATOMIC_H_ + +#ifdef __cplusplus + +// c++11 +#include + +using std::atomic_flag; +using std::atomic_long; + +#define ATOMIC_FLAG_TEST_AND_SET(p) ((p)->test_and_set()) +#define ATOMIC_FLAG_CLEAR(p) ((p)->clear()) + +#else + +#include "hplatform.h" // for HAVE_STDATOMIC_H +#if HAVE_STDATOMIC_H + +// c11 +#include + +#define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set +#define ATOMIC_FLAG_CLEAR atomic_flag_clear +#define ATOMIC_ADD atomic_fetch_add +#define ATOMIC_SUB atomic_fetch_sub +#define ATOMIC_INC(p) ATOMIC_ADD(p, 1) +#define ATOMIC_DEC(p) ATOMIC_SUB(p, 1) + +#else + +typedef volatile bool atomic_bool; +typedef volatile char atomic_char; +typedef volatile unsigned char atomic_uchar; +typedef volatile short atomic_short; +typedef volatile unsigned short atomic_ushort; +typedef volatile int atomic_int; +typedef volatile unsigned int atomic_uint; +typedef volatile long atomic_long; +typedef volatile unsigned long atomic_ulong; +typedef volatile long long atomic_llong; +typedef volatile unsigned long long atomic_ullong; +typedef volatile size_t atomic_size_t; + +typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; + +#ifdef _WIN32 + +#define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set +static inline bool atomic_flag_test_and_set(atomic_flag* p) { + // return InterlockedIncrement((LONG*)&p->_Value, 1); + return InterlockedCompareExchange((LONG*)&p->_Value, 1, 0); +} + +#define ATOMIC_ADD InterlockedAdd +#define ATOMIC_SUB(p, n) InterlockedAdd(p, -n) +#define ATOMIC_INC InterlockedIncrement +#define ATOMIC_DEC InterlockedDecrement + +#elif defined(__GNUC__) + +#define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set +static inline bool atomic_flag_test_and_set(atomic_flag* p) { + return !__sync_bool_compare_and_swap(&p->_Value, 0, 1); +} + +#define ATOMIC_ADD __sync_fetch_and_add +#define ATOMIC_SUB __sync_fetch_and_sub +#define ATOMIC_INC(p) ATOMIC_ADD(p, 1) +#define ATOMIC_DEC(p) ATOMIC_SUB(p, 1) + +#endif + +#endif // HAVE_STDATOMIC_H + +#endif // __cplusplus + +#ifndef ATOMIC_FLAG_INIT +#define ATOMIC_FLAG_INIT { 0 } +#endif + +#ifndef ATOMIC_VAR_INIT +#define ATOMIC_VAR_INIT(value) (value) +#endif + +#ifndef ATOMIC_FLAG_TEST_AND_SET +#define ATOMIC_FLAG_TEST_AND_SET atomic_flag_test_and_set +static inline bool atomic_flag_test_and_set(atomic_flag* p) { + bool ret = p->_Value; + p->_Value = 1; + return ret; +} +#endif + +#ifndef ATOMIC_FLAG_CLEAR +#define ATOMIC_FLAG_CLEAR atomic_flag_clear +static inline void atomic_flag_clear(atomic_flag* p) { + p->_Value = 0; +} +#endif + +#ifndef ATOMIC_ADD +#define ATOMIC_ADD(p, n) (*(p) += (n)) +#endif + +#ifndef ATOMIC_SUB +#define ATOMIC_SUB(p, n) (*(p) -= (n)) +#endif + +#ifndef ATOMIC_INC +#define ATOMIC_INC(p) ((*(p))++) +#endif + +#ifndef ATOMIC_DEC +#define ATOMIC_DEC(p) ((*(p))--) +#endif + +typedef atomic_flag hatomic_flag_t; +#define HATOMIC_FLAG_INIT ATOMIC_FLAG_INIT +#define hatomic_flag_test_and_set ATOMIC_FLAG_TEST_AND_SET +#define hatomic_flag_clear ATOMIC_FLAG_CLEAR + +typedef atomic_long hatomic_t; +#define HATOMIC_VAR_INIT ATOMIC_VAR_INIT +#define hatomic_add ATOMIC_ADD +#define hatomic_sub ATOMIC_SUB +#define hatomic_inc ATOMIC_INC +#define hatomic_dec ATOMIC_DEC + +#endif // HV_ATOMIC_H_ diff --git a/external/libhv/libhv-1.3.2/base/hbase.c b/external/libhv/libhv-1.3.2/base/hbase.c new file mode 100644 index 0000000..a7d600d --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hbase.c @@ -0,0 +1,519 @@ +#include "hbase.h" + +#ifdef OS_DARWIN +#include // for _NSGetExecutablePath +#endif + +#include "hatomic.h" + +#ifndef RAND_MAX +#define RAND_MAX 2147483647 +#endif + +static hatomic_t s_alloc_cnt = HATOMIC_VAR_INIT(0); +static hatomic_t s_free_cnt = HATOMIC_VAR_INIT(0); + +long hv_alloc_cnt() { + return s_alloc_cnt; +} + +long hv_free_cnt() { + return s_free_cnt; +} + +void* hv_malloc(size_t size) { + hatomic_inc(&s_alloc_cnt); + void* ptr = malloc(size); + if (!ptr) { + fprintf(stderr, "malloc failed!\n"); + exit(-1); + } + return ptr; +} + +void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize) { + hatomic_inc(&s_alloc_cnt); + if (oldptr) hatomic_inc(&s_free_cnt); + void* ptr = realloc(oldptr, newsize); + if (!ptr) { + fprintf(stderr, "realloc failed!\n"); + exit(-1); + } + if (newsize > oldsize) { + memset((char*)ptr + oldsize, 0, newsize - oldsize); + } + return ptr; +} + +void* hv_calloc(size_t nmemb, size_t size) { + hatomic_inc(&s_alloc_cnt); + void* ptr = calloc(nmemb, size); + if (!ptr) { + fprintf(stderr, "calloc failed!\n"); + exit(-1); + } + return ptr; +} + +void* hv_zalloc(size_t size) { + hatomic_inc(&s_alloc_cnt); + void* ptr = malloc(size); + if (!ptr) { + fprintf(stderr, "malloc failed!\n"); + exit(-1); + } + memset(ptr, 0, size); + return ptr; +} + +void hv_free(void* ptr) { + if (ptr) { + free(ptr); + ptr = NULL; + hatomic_inc(&s_free_cnt); + } +} + +char* hv_strupper(char* str) { + char* p = str; + while (*p != '\0') { + if (*p >= 'a' && *p <= 'z') { + *p &= ~0x20; + } + ++p; + } + return str; +} + +char* hv_strlower(char* str) { + char* p = str; + while (*p != '\0') { + if (*p >= 'A' && *p <= 'Z') { + *p |= 0x20; + } + ++p; + } + return str; +} + +char* hv_strreverse(char* str) { + if (str == NULL) return NULL; + char* b = str; + char* e = str; + while(*e) {++e;} + --e; + char tmp; + while (e > b) { + tmp = *e; + *e = *b; + *b = tmp; + --e; + ++b; + } + return str; +} + +// n = sizeof(dest_buf) +char* hv_strncpy(char* dest, const char* src, size_t n) { + assert(dest != NULL && src != NULL); + char* ret = dest; + while (*src != '\0' && --n > 0) { + *dest++ = *src++; + } + *dest = '\0'; + return ret; +} + +// n = sizeof(dest_buf) +char* hv_strncat(char* dest, const char* src, size_t n) { + assert(dest != NULL && src != NULL); + char* ret = dest; + while (*dest) {++dest;--n;} + while (*src != '\0' && --n > 0) { + *dest++ = *src++; + } + *dest = '\0'; + return ret; +} + +bool hv_strstartswith(const char* str, const char* start) { + assert(str != NULL && start != NULL); + while (*str && *start && *str == *start) { + ++str; + ++start; + } + return *start == '\0'; +} + +bool hv_strendswith(const char* str, const char* end) { + assert(str != NULL && end != NULL); + int len1 = 0; + int len2 = 0; + while (*str) {++str; ++len1;} + while (*end) {++end; ++len2;} + if (len1 < len2) return false; + while (len2-- > 0) { + --str; + --end; + if (*str != *end) { + return false; + } + } + return true; +} + +bool hv_strcontains(const char* str, const char* sub) { + assert(str != NULL && sub != NULL); + return strstr(str, sub) != NULL; +} + +bool hv_wildcard_match(const char* str, const char* pattern) { + assert(str != NULL && pattern != NULL); + bool match = false; + while (*str && *pattern) { + if (*pattern == '*') { + match = hv_strendswith(str, pattern + 1); + break; + } else if (*str != *pattern) { + match = false; + break; + } else { + ++str; + ++pattern; + } + } + return match ? match : (*str == '\0' && *pattern == '\0'); +} + +char* hv_strnchr(const char* s, char c, size_t n) { + assert(s != NULL); + const char* p = s; + while (*p != '\0' && n-- > 0) { + if (*p == c) return (char*)p; + ++p; + } + return NULL; +} + +char* hv_strrchr_dir(const char* filepath) { + char* p = (char*)filepath; + while (*p) ++p; + while (--p >= filepath) { +#ifdef OS_WIN + if (*p == '/' || *p == '\\') +#else + if (*p == '/') +#endif + return p; + } + return NULL; +} + +const char* hv_basename(const char* filepath) { + const char* pos = hv_strrchr_dir(filepath); + return pos ? pos+1 : filepath; +} + +const char* hv_suffixname(const char* filename) { + const char* pos = hv_strrchr_dot(filename); + return pos ? pos+1 : ""; +} + +int hv_mkdir_p(const char* dir) { + if (access(dir, 0) == 0) { + return EEXIST; + } + char tmp[MAX_PATH] = {0}; + hv_strncpy(tmp, dir, sizeof(tmp)); + char* p = tmp; + char delim = '/'; + while (*p) { +#ifdef OS_WIN + if (*p == '/' || *p == '\\') { + delim = *p; +#else + if (*p == '/') { +#endif + *p = '\0'; + hv_mkdir(tmp); + *p = delim; + } + ++p; + } + if (hv_mkdir(tmp) != 0) { + return EPERM; + } + return 0; +} + +int hv_rmdir_p(const char* dir) { + if (access(dir, 0) != 0) { + return ENOENT; + } + if (rmdir(dir) != 0) { + return EPERM; + } + char tmp[MAX_PATH] = {0}; + hv_strncpy(tmp, dir, sizeof(tmp)); + char* p = tmp; + while (*p) ++p; + while (--p >= tmp) { +#ifdef OS_WIN + if (*p == '/' || *p == '\\') { +#else + if (*p == '/') { +#endif + *p = '\0'; + if (rmdir(tmp) != 0) { + return 0; + } + } + } + return 0; +} + +bool hv_exists(const char* path) { + return access(path, 0) == 0; +} + +bool hv_isdir(const char* path) { + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + stat(path, &st); + return S_ISDIR(st.st_mode); +} + +bool hv_isfile(const char* path) { + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + stat(path, &st); + return S_ISREG(st.st_mode); +} + +bool hv_islink(const char* path) { +#ifdef OS_WIN + return hv_isdir(path) && (GetFileAttributes(path) & FILE_ATTRIBUTE_REPARSE_POINT); +#else + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + lstat(path, &st); + return S_ISLNK(st.st_mode); +#endif +} + +size_t hv_filesize(const char* filepath) { + struct stat st; + memset(&st, 0, sizeof(st)); + stat(filepath, &st); + return st.st_size; +} + +char* get_executable_path(char* buf, int size) { +#ifdef OS_WIN + GetModuleFileName(NULL, buf, size); +#elif defined(OS_LINUX) + if (readlink("/proc/self/exe", buf, size) == -1) { + return NULL; + } +#elif defined(OS_DARWIN) + _NSGetExecutablePath(buf, (uint32_t*)&size); +#endif + return buf; +} + +char* get_executable_dir(char* buf, int size) { + char filepath[MAX_PATH] = {0}; + get_executable_path(filepath, sizeof(filepath)); + char* pos = hv_strrchr_dir(filepath); + if (pos) { + *pos = '\0'; + strncpy(buf, filepath, size); + } + return buf; +} + +char* get_executable_file(char* buf, int size) { + char filepath[MAX_PATH] = {0}; + get_executable_path(filepath, sizeof(filepath)); + char* pos = hv_strrchr_dir(filepath); + if (pos) { + strncpy(buf, pos+1, size); + } + return buf; +} + +char* get_run_dir(char* buf, int size) { + return getcwd(buf, size); +} + +int hv_rand(int min, int max) { + static int s_seed = 0; + assert(max > min); + + if (s_seed == 0) { + s_seed = time(NULL); + srand(s_seed); + } + + int _rand = rand(); + _rand = min + (int) ((double) ((double) (max) - (min) + 1.0) * ((_rand) / ((RAND_MAX) + 1.0))); + return _rand; +} + +char* hv_random_string(char *buf, int len) { + static char s_characters[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', + 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + }; + int i = 0; + for (; i < len; i++) { + buf[i] = s_characters[hv_rand(0, sizeof(s_characters) - 1)]; + } + buf[i] = '\0'; + return buf; +} + +bool hv_getboolean(const char* str) { + if (str == NULL) return false; + int len = strlen(str); + if (len == 0) return false; + switch (len) { + case 1: return *str == '1' || *str == 'y' || *str == 'Y'; + case 2: return stricmp(str, "on") == 0; + case 3: return stricmp(str, "yes") == 0; + case 4: return stricmp(str, "true") == 0; + case 6: return stricmp(str, "enable") == 0; + default: return false; + } +} + +size_t hv_parse_size(const char* str) { + size_t size = 0, n = 0; + const char* p = str; + char c; + while ((c = *p) != '\0') { + if (c >= '0' && c <= '9') { + n = n * 10 + c - '0'; + } else { + switch (c) { + case 'K': case 'k': n <<= 10; break; + case 'M': case 'm': n <<= 20; break; + case 'G': case 'g': n <<= 30; break; + case 'T': case 't': n <<= 40; break; + default: break; + } + size += n; + n = 0; + } + ++p; + } + return size + n; +} + +time_t hv_parse_time(const char* str) { + time_t time = 0, n = 0; + const char* p = str; + char c; + while ((c = *p) != '\0') { + if (c >= '0' && c <= '9') { + n = n * 10 + c - '0'; + } else { + switch (c) { + case 's': break; + case 'm': n *= 60; break; + case 'h': n *= 60 * 60; break; + case 'd': n *= 24 * 60 * 60; break; + case 'w': n *= 7 * 24 * 60 * 60; break; + default: break; + } + time += n; + n = 0; + } + ++p; + } + return time + n; +} + +int hv_parse_url(hurl_t* stURL, const char* strURL) { + if (stURL == NULL || strURL == NULL) return -1; + memset(stURL, 0, sizeof(hurl_t)); + const char* begin = strURL; + const char* end = strURL; + while (*end != '\0') ++end; + if (end - begin > 65535) return -2; + // scheme:// + const char* sp = strURL; + const char* ep = strstr(sp, "://"); + if (ep) { + // stURL->fields[HV_URL_SCHEME].off = sp - begin; + stURL->fields[HV_URL_SCHEME].len = ep - sp; + sp = ep + 3; + } + // user:pswd@host:port + ep = strchr(sp, '/'); + if (ep == NULL) ep = end; + const char* user = sp; + const char* host = sp; + const char* pos = hv_strnchr(sp, '@', ep - sp); + if (pos) { + // user:pswd + const char* pswd = hv_strnchr(user, ':', pos - user); + if (pswd) { + stURL->fields[HV_URL_PASSWORD].off = pswd + 1 - begin; + stURL->fields[HV_URL_PASSWORD].len = pos - pswd - 1; + } else { + pswd = pos; + } + stURL->fields[HV_URL_USERNAME].off = user - begin; + stURL->fields[HV_URL_USERNAME].len = pswd - user; + // @ + host = pos + 1; + } + // port + const char* port = hv_strnchr(host, ':', ep - host); + if (port) { + stURL->fields[HV_URL_PORT].off = port + 1 - begin; + stURL->fields[HV_URL_PORT].len = ep - port - 1; + // atoi + for (unsigned short i = 1; i <= stURL->fields[HV_URL_PORT].len; ++i) { + stURL->port = stURL->port * 10 + (port[i] - '0'); + } + } else { + port = ep; + // set default port + stURL->port = 80; + if (stURL->fields[HV_URL_SCHEME].len > 0) { + if (strncmp(strURL, "https://", 8) == 0) { + stURL->port = 443; + } + } + } + // host + stURL->fields[HV_URL_HOST].off = host - begin; + stURL->fields[HV_URL_HOST].len = port - host; + if (ep == end) return 0; + // /path + sp = ep; + ep = strchr(sp, '?'); + if (ep == NULL) ep = end; + stURL->fields[HV_URL_PATH].off = sp - begin; + stURL->fields[HV_URL_PATH].len = ep - sp; + if (ep == end) return 0; + // ?query + sp = ep + 1; + ep = strchr(sp, '#'); + if (ep == NULL) ep = end; + stURL->fields[HV_URL_QUERY].off = sp - begin; + stURL->fields[HV_URL_QUERY].len = ep - sp; + if (ep == end) return 0; + // #fragment + sp = ep + 1; + ep = end; + stURL->fields[HV_URL_FRAGMENT].off = sp - begin; + stURL->fields[HV_URL_FRAGMENT].len = ep - sp; + return 0; +} diff --git a/external/libhv/libhv-1.3.2/base/hbase.h b/external/libhv/libhv-1.3.2/base/hbase.h new file mode 100644 index 0000000..1a9041a --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hbase.h @@ -0,0 +1,144 @@ +#ifndef HV_BASE_H_ +#define HV_BASE_H_ + +#include "hexport.h" +#include "hplatform.h" // for bool +#include "hdef.h" // for printd + +BEGIN_EXTERN_C + +//--------------------alloc/free--------------------------- +HV_EXPORT void* hv_malloc(size_t size); +HV_EXPORT void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize); +HV_EXPORT void* hv_calloc(size_t nmemb, size_t size); +HV_EXPORT void* hv_zalloc(size_t size); +HV_EXPORT void hv_free(void* ptr); + +#define HV_ALLOC(ptr, size)\ + do {\ + *(void**)&(ptr) = hv_zalloc(size);\ + printd("alloc(%p, size=%llu)\tat [%s:%d:%s]\n", ptr, (unsigned long long)size, __FILE__, __LINE__, __FUNCTION__);\ + } while(0) + +#define HV_ALLOC_SIZEOF(ptr) HV_ALLOC(ptr, sizeof(*(ptr))) + +#define HV_FREE(ptr)\ + do {\ + if (ptr) {\ + hv_free(ptr);\ + printd("free( %p )\tat [%s:%d:%s]\n", ptr, __FILE__, __LINE__, __FUNCTION__);\ + ptr = NULL;\ + }\ + } while(0) + +#define STACK_OR_HEAP_ALLOC(ptr, size, stack_size)\ + unsigned char _stackbuf_[stack_size] = { 0 };\ + if ((size) > (stack_size)) {\ + HV_ALLOC(ptr, size);\ + } else {\ + *(unsigned char**)&(ptr) = _stackbuf_;\ + } + +#define STACK_OR_HEAP_FREE(ptr)\ + if ((unsigned char*)(ptr) != _stackbuf_) {\ + HV_FREE(ptr);\ + } + +#define HV_DEFAULT_STACKBUF_SIZE 1024 +#define HV_STACK_ALLOC(ptr, size) STACK_OR_HEAP_ALLOC(ptr, size, HV_DEFAULT_STACKBUF_SIZE) +#define HV_STACK_FREE(ptr) STACK_OR_HEAP_FREE(ptr) + +HV_EXPORT long hv_alloc_cnt(); +HV_EXPORT long hv_free_cnt(); +HV_INLINE void hv_memcheck(void) { + printf("Memcheck => alloc:%ld free:%ld\n", hv_alloc_cnt(), hv_free_cnt()); +} +#define HV_MEMCHECK atexit(hv_memcheck); + +//--------------------string------------------------------- +HV_EXPORT char* hv_strupper(char* str); +HV_EXPORT char* hv_strlower(char* str); +HV_EXPORT char* hv_strreverse(char* str); + +HV_EXPORT bool hv_strstartswith(const char* str, const char* start); +HV_EXPORT bool hv_strendswith(const char* str, const char* end); +HV_EXPORT bool hv_strcontains(const char* str, const char* sub); +HV_EXPORT bool hv_wildcard_match(const char* str, const char* pattern); + +// strncpy n = sizeof(dest_buf)-1 +// hv_strncpy n = sizeof(dest_buf) +HV_EXPORT char* hv_strncpy(char* dest, const char* src, size_t n); + +// strncat n = sizeof(dest_buf)-1-strlen(dest) +// hv_strncpy n = sizeof(dest_buf) +HV_EXPORT char* hv_strncat(char* dest, const char* src, size_t n); + +#if !HAVE_STRLCPY +#define strlcpy hv_strncpy +#endif + +#if !HAVE_STRLCAT +#define strlcat hv_strncat +#endif + +HV_EXPORT char* hv_strnchr(const char* s, char c, size_t n); + +#define hv_strrchr_dot(str) strrchr(str, '.') +HV_EXPORT char* hv_strrchr_dir(const char* filepath); + +// basename +HV_EXPORT const char* hv_basename(const char* filepath); +HV_EXPORT const char* hv_suffixname(const char* filename); +// mkdir -p +HV_EXPORT int hv_mkdir_p(const char* dir); +// rmdir -p +HV_EXPORT int hv_rmdir_p(const char* dir); +// path +HV_EXPORT bool hv_exists(const char* path); +HV_EXPORT bool hv_isdir(const char* path); +HV_EXPORT bool hv_isfile(const char* path); +HV_EXPORT bool hv_islink(const char* path); +HV_EXPORT size_t hv_filesize(const char* filepath); + +HV_EXPORT char* get_executable_path(char* buf, int size); +HV_EXPORT char* get_executable_dir(char* buf, int size); +HV_EXPORT char* get_executable_file(char* buf, int size); +HV_EXPORT char* get_run_dir(char* buf, int size); + +// random +HV_EXPORT int hv_rand(int min, int max); +HV_EXPORT char* hv_random_string(char *buf, int len); + +// 1 y on yes true enable => true +HV_EXPORT bool hv_getboolean(const char* str); +// 1T2G3M4K5B => ?B +HV_EXPORT size_t hv_parse_size(const char* str); +// 1w2d3h4m5s => ?s +HV_EXPORT time_t hv_parse_time(const char* str); + +// scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] +typedef enum { + HV_URL_SCHEME, + HV_URL_USERNAME, + HV_URL_PASSWORD, + HV_URL_HOST, + HV_URL_PORT, + HV_URL_PATH, + HV_URL_QUERY, + HV_URL_FRAGMENT, + HV_URL_FIELD_NUM, +} hurl_field_e; + +typedef struct hurl_s { + struct { + unsigned short off; + unsigned short len; + } fields[HV_URL_FIELD_NUM]; + unsigned short port; +} hurl_t; + +HV_EXPORT int hv_parse_url(hurl_t* stURL, const char* strURL); + +END_EXTERN_C + +#endif // HV_BASE_H_ diff --git a/external/libhv/libhv-1.3.2/base/hbuf.h b/external/libhv/libhv-1.3.2/base/hbuf.h new file mode 100644 index 0000000..903e164 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hbuf.h @@ -0,0 +1,257 @@ +#ifndef HV_BUF_H_ +#define HV_BUF_H_ + +#include "hdef.h" // for MAX +#include "hbase.h" // for HV_ALLOC, HV_FREE + +typedef struct hbuf_s { + char* base; + size_t len; + +#ifdef __cplusplus + hbuf_s() { + base = NULL; + len = 0; + } + + hbuf_s(void* data, size_t len) { + this->base = (char*)data; + this->len = len; + } +#endif +} hbuf_t; + +typedef struct offset_buf_s { + char* base; + size_t len; + size_t offset; +#ifdef __cplusplus + offset_buf_s() { + base = NULL; + len = 0; + offset = 0; + } + + offset_buf_s(void* data, size_t len) { + this->base = (char*)data; + this->len = len; + offset = 0; + } +#endif +} offset_buf_t; + +typedef struct fifo_buf_s { + char* base; + size_t len; + size_t head; + size_t tail; +#ifdef __cplusplus + fifo_buf_s() { + base = NULL; + len = 0; + head = tail = 0; + } + + fifo_buf_s(void* data, size_t len) { + this->base = (char*)data; + this->len = len; + head = tail = 0; + } +#endif +} fifo_buf_t; + +#ifdef __cplusplus +class HBuf : public hbuf_t { +public: + HBuf() : hbuf_t() { + cleanup_ = false; + } + HBuf(void* data, size_t len) : hbuf_t(data, len) { + cleanup_ = false; + } + HBuf(size_t cap) { resize(cap); } + + virtual ~HBuf() { + cleanup(); + } + + void* data() { return base; } + size_t size() { return len; } + + bool isNull() { return base == NULL || len == 0; } + + void cleanup() { + if (cleanup_) { + HV_FREE(base); + len = 0; + cleanup_ = false; + } + } + + void resize(size_t cap) { + if (cap == len) return; + + if (base == NULL) { + HV_ALLOC(base, cap); + } + else { + base = (char*)hv_realloc(base, cap, len); + } + len = cap; + cleanup_ = true; + } + + void copy(void* data, size_t len) { + resize(len); + memcpy(base, data, len); + } + + void copy(hbuf_t* buf) { + copy(buf->base, buf->len); + } + +private: + bool cleanup_; +}; + +// VL: Variable-Length +class HVLBuf : public HBuf { +public: + HVLBuf() : HBuf() {_offset = _size = 0;} + HVLBuf(void* data, size_t len) : HBuf(data, len) {_offset = 0; _size = len;} + HVLBuf(size_t cap) : HBuf(cap) {_offset = _size = 0;} + virtual ~HVLBuf() {} + + char* data() { return base + _offset; } + size_t size() { return _size; } + + void push_front(void* ptr, size_t len) { + if (len > this->len - _size) { + size_t newsize = MAX(this->len, len)*2; + resize(newsize); + } + + if (_offset < len) { + // move => end + memmove(base+this->len-_size, data(), _size); + _offset = this->len-_size; + } + + memcpy(data()-len, ptr, len); + _offset -= len; + _size += len; + } + + void push_back(void* ptr, size_t len) { + if (len > this->len - _size) { + size_t newsize = MAX(this->len, len)*2; + resize(newsize); + } + else if (len > this->len - _offset - _size) { + // move => start + memmove(base, data(), _size); + _offset = 0; + } + memcpy(data()+_size, ptr, len); + _size += len; + } + + void pop_front(void* ptr, size_t len) { + if (len <= _size) { + if (ptr) { + memcpy(ptr, data(), len); + } + _offset += len; + if (_offset >= this->len) _offset = 0; + _size -= len; + } + } + + void pop_back(void* ptr, size_t len) { + if (len <= _size) { + if (ptr) { + memcpy(ptr, data()+_size-len, len); + } + _size -= len; + } + } + + void clear() { + _offset = _size = 0; + } + + void prepend(void* ptr, size_t len) { + push_front(ptr, len); + } + + void append(void* ptr, size_t len) { + push_back(ptr, len); + } + + void insert(void* ptr, size_t len) { + push_back(ptr, len); + } + + void remove(size_t len) { + pop_front(NULL, len); + } + +private: + size_t _offset; + size_t _size; +}; + +class HRingBuf : public HBuf { +public: + HRingBuf() : HBuf() {_head = _tail = _size = 0;} + HRingBuf(size_t cap) : HBuf(cap) {_head = _tail = _size = 0;} + virtual ~HRingBuf() {} + + char* alloc(size_t len) { + char* ret = NULL; + if (_head < _tail || _size == 0) { + // [_tail, this->len) && [0, _head) + if (this->len - _tail >= len) { + ret = base + _tail; + _tail += len; + if (_tail == this->len) _tail = 0; + } + else if (_head >= len) { + ret = base; + _tail = len; + } + } + else { + // [_tail, _head) + if (_head - _tail >= len) { + ret = base + _tail; + _tail += len; + } + } + _size += ret ? len : 0; + return ret; + } + + void free(size_t len) { + _size -= len; + if (len <= this->len - _head) { + _head += len; + if (_head == this->len) _head = 0; + } + else { + _head = len; + } + } + + void clear() {_head = _tail = _size = 0;} + + size_t size() {return _size;} + +private: + size_t _head; + size_t _tail; + size_t _size; +}; +#endif + +#endif // HV_BUF_H_ diff --git a/external/libhv/libhv-1.3.2/base/hdef.h b/external/libhv/libhv-1.3.2/base/hdef.h new file mode 100644 index 0000000..0f79c75 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hdef.h @@ -0,0 +1,271 @@ +#ifndef HV_DEF_H_ +#define HV_DEF_H_ + +#include "hplatform.h" + +#ifndef ABS +#define ABS(n) ((n) > 0 ? (n) : -(n)) +#endif + +#ifndef NABS +#define NABS(n) ((n) < 0 ? (n) : -(n)) +#endif + +#ifndef ARRAY_SIZE +#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*(a))) +#endif + +#ifndef BITSET +#define BITSET(p, n) (*(p) |= (1u << (n))) +#endif + +#ifndef BITCLR +#define BITCLR(p, n) (*(p) &= ~(1u << (n))) +#endif + +#ifndef BITGET +#define BITGET(i, n) ((i) & (1u << (n))) +#endif + +/* +#ifndef CR +#define CR '\r' +#endif + +#ifndef LF +#define LF '\n' +#endif + +#ifndef CRLF +#define CRLF "\r\n" +#endif +*/ + +#define FLOAT_PRECISION 1e-6 +#define FLOAT_EQUAL_ZERO(f) (ABS(f) < FLOAT_PRECISION) + +#ifndef INFINITE +#define INFINITE (uint32_t)-1 +#endif + +/* +ASCII: +[0, 0x20) control-charaters +[0x20, 0x7F) printable-charaters + +0x0A => LF +0x0D => CR +0x20 => SPACE +0x7F => DEL + +[0x09, 0x0D] => \t\n\v\f\r +[0x30, 0x39] => 0~9 +[0x41, 0x5A] => A~Z +[0x61, 0x7A] => a~z +*/ + +#ifndef IS_ALPHA +#define IS_ALPHA(c) (((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z')) +#endif + +// NOTE: IS_NUM conflicts with mysql.h +#ifndef IS_DIGIT +#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9') +#endif + +#ifndef IS_ALPHANUM +#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_DIGIT(c)) +#endif + +#ifndef IS_CNTRL +#define IS_CNTRL(c) ((c) >= 0 && (c) < 0x20) +#endif + +#ifndef IS_GRAPH +#define IS_GRAPH(c) ((c) >= 0x20 && (c) < 0x7F) +#endif + +#ifndef IS_HEX +#define IS_HEX(c) (IS_DIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) +#endif + +#ifndef IS_LOWER +#define IS_LOWER(c) (((c) >= 'a' && (c) <= 'z')) +#endif + +#ifndef IS_UPPER +#define IS_UPPER(c) (((c) >= 'A' && (c) <= 'Z')) +#endif + +#ifndef LOWER +#define LOWER(c) ((c) | 0x20) +#endif + +#ifndef UPPER +#define UPPER(c) ((c) & ~0x20) +#endif + +// LD, LU, LLD, LLU for explicit conversion of integer +// #ifndef LD +// #define LD(v) ((long)(v)) +// #endif + +// #ifndef LU +// #define LU(v) ((unsigned long)(v)) +// #endif + +#ifndef LLD +#define LLD(v) ((long long)(v)) +#endif + +#ifndef LLU +#define LLU(v) ((unsigned long long)(v)) +#endif + +#ifndef _WIN32 + +// MAKEWORD, HIBYTE, LOBYTE +#ifndef MAKEWORD +#define MAKEWORD(h, l) ( (((WORD)h) << 8) | (l & 0xff) ) +#endif + +#ifndef HIBYTE +#define HIBYTE(w) ( (BYTE)(((WORD)w) >> 8) ) +#endif + +#ifndef LOBYTE +#define LOBYTE(w) ( (BYTE)(w & 0xff) ) +#endif + +// MAKELONG, HIWORD, LOWORD +#ifndef MAKELONG +#define MAKELONG(h, l) ( ((int32_t)h) << 16 | (l & 0xffff) ) +#endif + +#ifndef HIWORD +#define HIWORD(n) ( (WORD)(((int32_t)n) >> 16) ) +#endif + +#ifndef LOWORD +#define LOWORD(n) ( (WORD)(n & 0xffff) ) +#endif + +#endif // _WIN32 + +// MAKEINT64, HIINT, LOINT +#ifndef MAKEINT64 +#define MAKEINT64(h, l) ( ((int64_t)h) << 32 | (l & 0xffffffff) ) +#endif + +#ifndef HIINT +#define HIINT(n) ( (int32_t)(((int64_t)n) >> 32) ) +#endif + +#ifndef LOINT +#define LOINT(n) ( (int32_t)(n & 0xffffffff) ) +#endif + +#ifndef MAKE_FOURCC +#define MAKE_FOURCC(a, b, c, d) \ +( ((uint32)d) | ( ((uint32)c) << 8 ) | ( ((uint32)b) << 16 ) | ( ((uint32)a) << 24 ) ) +#endif + +#ifndef MAX +#define MAX(a, b) ((a) > (b) ? (a) : (b)) +#endif + +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef LIMIT +#define LIMIT(lower, v, upper) ((v) < (lower) ? (lower) : (v) > (upper) ? (upper) : (v)) +#endif + +#ifndef MAX_PATH +#define MAX_PATH 260 +#endif + +#ifndef NULL +#ifdef __cplusplus + #define NULL 0 +#else + #define NULL ((void*)0) +#endif +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef SAFE_ALLOC +#define SAFE_ALLOC(p, size)\ + do {\ + void* ptr = malloc(size);\ + if (!ptr) {\ + fprintf(stderr, "malloc failed!\n");\ + exit(-1);\ + }\ + memset(ptr, 0, size);\ + *(void**)&(p) = ptr;\ + } while(0) +#endif + +#ifndef SAFE_FREE +#define SAFE_FREE(p) do {if (p) {free(p); (p) = NULL;}} while(0) +#endif + +#ifndef SAFE_DELETE +#define SAFE_DELETE(p) do {if (p) {delete (p); (p) = NULL;}} while(0) +#endif + +#ifndef SAFE_DELETE_ARRAY +#define SAFE_DELETE_ARRAY(p) do {if (p) {delete[] (p); (p) = NULL;}} while(0) +#endif + +#ifndef SAFE_RELEASE +#define SAFE_RELEASE(p) do {if (p) {(p)->release(); (p) = NULL;}} while(0) +#endif + +#ifndef SAFE_CLOSE +#define SAFE_CLOSE(fd) do {if ((fd) >= 0) {close(fd); (fd) = -1;}} while(0) +#endif + +#define STRINGIFY(x) STRINGIFY_HELPER(x) +#define STRINGIFY_HELPER(x) #x + +#define STRINGCAT(x, y) STRINGCAT_HELPER(x, y) +#define STRINGCAT_HELPER(x, y) x##y + +#ifndef offsetof +#define offsetof(type, member) \ +((size_t)(&((type*)0)->member)) +#endif + +#ifndef offsetofend +#define offsetofend(type, member) \ +(offsetof(type, member) + sizeof(((type*)0)->member)) +#endif + +#ifndef container_of +#define container_of(ptr, type, member) \ +((type*)((char*)(ptr) - offsetof(type, member))) +#endif + +#ifdef PRINT_DEBUG +#define printd(...) printf(__VA_ARGS__) +#else +#define printd(...) +#endif + +#ifdef PRINT_ERROR +#define printe(...) fprintf(stderr, __VA_ARGS__) +#else +#define printe(...) +#endif + +#endif // HV_DEF_H_ diff --git a/external/libhv/libhv-1.3.2/base/heap.h b/external/libhv/libhv-1.3.2/base/heap.h new file mode 100644 index 0000000..a0c5b56 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/heap.h @@ -0,0 +1,172 @@ +#ifndef HV_HEAP_H_ +#define HV_HEAP_H_ + +#include // for assert +#include // for NULL + +struct heap_node { + struct heap_node* parent; + struct heap_node* left; + struct heap_node* right; +}; + +typedef int (*heap_compare_fn)(const struct heap_node* lhs, const struct heap_node* rhs); +struct heap { + struct heap_node* root; + int nelts; + // if compare is less_than, root is min of heap + // if compare is larger_than, root is max of heap + heap_compare_fn compare; +}; + +static inline void heap_init(struct heap* heap, heap_compare_fn fn) { + heap->root = NULL; + heap->nelts = 0; + heap->compare = fn; +} + +// replace s with r +static inline void heap_replace(struct heap* heap, struct heap_node* s, struct heap_node* r) { + // s->parent->child, s->left->parent, s->right->parent + if (s->parent == NULL) heap->root = r; + else if (s->parent->left == s) s->parent->left = r; + else if (s->parent->right == s) s->parent->right = r; + + if (s->left) s->left->parent = r; + if (s->right) s->right->parent = r; + if (r) { + //*r = *s; + r->parent = s->parent; + r->left = s->left; + r->right = s->right; + } +} + +static inline void heap_swap(struct heap* heap, struct heap_node* parent, struct heap_node* child) { + assert(child->parent == parent && (parent->left == child || parent->right == child)); + struct heap_node* pparent = parent->parent; + struct heap_node* lchild = child->left; + struct heap_node* rchild = child->right; + struct heap_node* sibling = NULL; + + if (pparent == NULL) heap->root = child; + else if (pparent->left == parent) pparent->left = child; + else if (pparent->right == parent) pparent->right = child; + + if (lchild) lchild->parent = parent; + if (rchild) rchild->parent = parent; + + child->parent = pparent; + if (parent->left == child) { + sibling = parent->right; + child->left = parent; + child->right = sibling; + } else { + sibling = parent->left; + child->left = sibling; + child->right = parent; + } + if (sibling) sibling->parent = child; + + parent->parent = child; + parent->left = lchild; + parent->right = rchild; +} + +static inline void heap_insert(struct heap* heap, struct heap_node* node) { + // get last => insert node => sift up + // 0: left, 1: right + int path = 0; + int n,d; + ++heap->nelts; + // traverse from bottom to up, get path of last node + for (d = 0, n = heap->nelts; n >= 2; ++d, n>>=1) { + path = (path << 1) | (n & 1); + } + + // get last->parent by path + struct heap_node* parent = heap->root; + while(d > 1) { + parent = (path & 1) ? parent->right : parent->left; + --d; + path >>= 1; + } + + // insert node + node->parent = parent; + if (parent == NULL) heap->root = node; + else if (path & 1) parent->right = node; + else parent->left = node; + + // sift up + if (heap->compare) { + while (node->parent && heap->compare(node, node->parent)) { + heap_swap(heap, node->parent, node); + } + } +} + +static inline void heap_remove(struct heap* heap, struct heap_node* node) { + if (heap->nelts == 0) return; + // get last => replace node with last => sift down and sift up + // 0: left, 1: right + int path = 0; + int n,d; + // traverse from bottom to up, get path of last node + for (d = 0, n = heap->nelts; n >= 2; ++d, n>>=1) { + path = (path << 1) | (n & 1); + } + --heap->nelts; + + // get last->parent by path + struct heap_node* parent = heap->root; + while(d > 1) { + parent = (path & 1) ? parent->right : parent->left; + --d; + path >>= 1; + } + + // replace node with last + struct heap_node* last = NULL; + if (parent == NULL) { + return; + } + else if (path & 1) { + last = parent->right; + parent->right = NULL; + } + else { + last = parent->left; + parent->left = NULL; + } + if (last == NULL) { + if (heap->root == node) { + heap->root = NULL; + } + return; + } + heap_replace(heap, node, last); + node->parent = node->left = node->right = NULL; + + if (!heap->compare) return; + struct heap_node* v = last; + struct heap_node* est = NULL; + // sift down + while (1) { + est = v; + if (v->left) est = heap->compare(est, v->left) ? est : v->left; + if (v->right) est = heap->compare(est, v->right) ? est : v->right; + if (est == v) break; + heap_swap(heap, v, est); + } + // sift up + while (v->parent && heap->compare(v, v->parent)) { + heap_swap(heap, v->parent, v); + } +} + +static inline void heap_dequeue(struct heap* heap) { + heap_remove(heap, heap->root); +} + +#endif // HV_HEAP_H_ diff --git a/external/libhv/libhv-1.3.2/base/hendian.h b/external/libhv/libhv-1.3.2/base/hendian.h new file mode 100644 index 0000000..573af6c --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hendian.h @@ -0,0 +1,244 @@ +#ifndef HV_ENDIAN_H_ +#define HV_ENDIAN_H_ + +#include "hplatform.h" +#if defined(OS_MAC) +#include +#define htobe16(v) OSSwapHostToBigInt16(v) +#define htobe32(v) OSSwapHostToBigInt32(v) +#define htobe64(v) OSSwapHostToBigInt64(v) +#define be16toh(v) OSSwapBigToHostInt16(v) +#define be32toh(v) OSSwapBigToHostInt32(v) +#define be64toh(v) OSSwapBigToHostInt64(v) + +#define htole16(v) OSSwapHostToLittleInt16(v) +#define htole32(v) OSSwapHostToLittleInt32(v) +#define htole64(v) OSSwapHostToLittleInt64(v) +#define le16toh(v) OSSwapLittleToHostInt16(v) +#define le32toh(v) OSSwapLittleToHostInt32(v) +#define le64toh(v) OSSwapLittleToHostInt64(v) +#elif defined(OS_WIN) + +#if _WIN32_WINNT < _WIN32_WINNT_WIN8 + /* + * Byte order conversion functions for 64-bit integers and 32 + 64 bit + * floating-point numbers. IEEE big-endian format is used for the + * network floating point format. + */ + #define _WS2_32_WINSOCK_SWAP_LONG(l) \ + ( ( ((l) >> 24) & 0x000000FFL ) | \ + ( ((l) >> 8) & 0x0000FF00L ) | \ + ( ((l) << 8) & 0x00FF0000L ) | \ + ( ((l) << 24) & 0xFF000000L ) ) + + #define _WS2_32_WINSOCK_SWAP_LONGLONG(l) \ + ( ( ((l) >> 56) & 0x00000000000000FFLL ) | \ + ( ((l) >> 40) & 0x000000000000FF00LL ) | \ + ( ((l) >> 24) & 0x0000000000FF0000LL ) | \ + ( ((l) >> 8) & 0x00000000FF000000LL ) | \ + ( ((l) << 8) & 0x000000FF00000000LL ) | \ + ( ((l) << 24) & 0x0000FF0000000000LL ) | \ + ( ((l) << 40) & 0x00FF000000000000LL ) | \ + ( ((l) << 56) & 0xFF00000000000000LL ) ) + + + #ifndef htonll + __inline unsigned __int64 htonll ( unsigned __int64 Value ) + { + const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); + return Retval; + } + #endif /* htonll */ + + #ifndef ntohll + __inline unsigned __int64 ntohll ( unsigned __int64 Value ) + { + const unsigned __int64 Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); + return Retval; + } + #endif /* ntohll */ + + #ifndef htonf + __inline unsigned __int32 htonf ( float Value ) + { + unsigned __int32 Tempval; + unsigned __int32 Retval; + Tempval = *(unsigned __int32*)(&Value); + Retval = _WS2_32_WINSOCK_SWAP_LONG (Tempval); + return Retval; + } + #endif /* htonf */ + + #ifndef ntohf + __inline float ntohf ( unsigned __int32 Value ) + { + const unsigned __int32 Tempval = _WS2_32_WINSOCK_SWAP_LONG (Value); + float Retval; + *((unsigned __int32*)&Retval) = Tempval; + return Retval; + } + #endif /* ntohf */ + + #ifndef htond + __inline unsigned __int64 htond ( double Value ) + { + unsigned __int64 Tempval; + unsigned __int64 Retval; + Tempval = *(unsigned __int64*)(&Value); + Retval = _WS2_32_WINSOCK_SWAP_LONGLONG (Tempval); + return Retval; + } + #endif /* htond */ + + #ifndef ntohd + __inline double ntohd ( unsigned __int64 Value ) + { + const unsigned __int64 Tempval = _WS2_32_WINSOCK_SWAP_LONGLONG (Value); + double Retval; + *((unsigned __int64*)&Retval) = Tempval; + return Retval; + } + #endif /* ntohd */ +#endif + +#define htobe16(v) htons(v) +#define htobe32(v) htonl(v) +#define htobe64(v) htonll(v) +#define be16toh(v) ntohs(v) +#define be32toh(v) ntohl(v) +#define be64toh(v) ntohll(v) + +#if (BYTE_ORDER == LITTLE_ENDIAN) +#define htole16(v) (v) +#define htole32(v) (v) +#define htole64(v) (v) +#define le16toh(v) (v) +#define le32toh(v) (v) +#define le64toh(v) (v) +#elif (BYTE_ORDER == BIG_ENDIAN) +#define htole16(v) __builtin_bswap16(v) +#define htole32(v) __builtin_bswap32(v) +#define htole64(v) __builtin_bswap64(v) +#define le16toh(v) __builtin_bswap16(v) +#define le32toh(v) __builtin_bswap32(v) +#define le64toh(v) __builtin_bswap64(v) +#endif +#elif HAVE_ENDIAN_H +#include +#elif HAVE_SYS_ENDIAN_H +#include +#else +#warning "Not found endian.h!" +#endif + +#define PI8(p) *(int8_t*)(p) +#define PI16(p) *(int16_t*)(p) +#define PI32(p) *(int32_t*)(p) +#define PI64(p) *(int64_t*)(p) + +#define PU8(p) *(uint8_t*)(p) +#define PU16(p) *(uint16_t*)(p) +#define PU32(p) *(uint32_t*)(p) +#define PU64(p) *(uint64_t*)(p) + +#define PF32(p) *(float*)(p) +#define PF64(p) *(double*)(p) + +#define GET_BE16(p) be16toh(PU16(p)) +#define GET_BE32(p) be32toh(PU32(p)) +#define GET_BE64(p) be64toh(PU64(p)) + +#define GET_LE16(p) le16toh(PU16(p)) +#define GET_LE32(p) le32toh(PU32(p)) +#define GET_LE64(p) le64toh(PU64(p)) + +#define PUT_BE16(p, v) PU16(p) = htobe16(v) +#define PUT_BE32(p, v) PU32(p) = htobe32(v) +#define PUT_BE64(p, v) PU64(p) = htobe64(v) + +#define PUT_LE16(p, v) PU16(p) = htole16(v) +#define PUT_LE32(p, v) PU32(p) = htole32(v) +#define PUT_LE64(p, v) PU64(p) = htole64(v) + +// NOTE: uint8_t* p = (uint8_t*)buf; +#define POP_BE8(p, v) v = *p; ++p +#define POP_BE16(p, v) v = be16toh(PU16(p)); p += 2 +#define POP_BE32(p, v) v = be32toh(PU32(p)); p += 4 +#define POP_BE64(p, v) v = be64toh(PU64(p)); p += 8 + +#define POP_LE8(p, v) v= *p; ++p +#define POP_LE16(p, v) v = le16toh(PU16(p)); p += 2 +#define POP_LE32(p, v) v = le32toh(PU32(p)); p += 4 +#define POP_LE64(p, v) v = le64toh(PU64(p)); p += 8 + +#define PUSH_BE8(p, v) *p = v; ++p +#define PUSH_BE16(p, v) PU16(p) = htobe16(v); p += 2 +#define PUSH_BE32(p, v) PU32(p) = htobe32(v); p += 4 +#define PUSH_BE64(p, v) PU64(p) = htobe64(v); p += 8 + +#define PUSH_LE8(p, v) *p = v; ++p +#define PUSH_LE16(p, v) PU16(p) = htole16(v); p += 2 +#define PUSH_LE32(p, v) PU32(p) = htole32(v); p += 4 +#define PUSH_LE64(p, v) PU64(p) = htole64(v); p += 8 + +// NOTE: NET_ENDIAN = BIG_ENDIAN +#define POP8(p, v) POP_BE8(p, v) +#define POP16(p, v) POP_BE16(p, v) +#define POP32(p, v) POP_BE32(p, v) +#define POP64(p, v) POP_BE64(p, v) +#define POP_N(p, v, n) memcpy(v, p, n); p += n + +#define PUSH8(p, v) PUSH_BE8(p, v) +#define PUSH16(p, v) PUSH_BE16(p, v) +#define PUSH32(p, v) PUSH_BE32(p, v) +#define PUSH64(p, v) PUSH_BE64(p, v) +#define PUSH_N(p, v, n) memcpy(p, v, n); p += n + +static inline int detect_endian() { + union { + char c; + short s; + } u; + u.s = 0x1122; + return u.c ==0x11 ? BIG_ENDIAN : LITTLE_ENDIAN; +} + +#ifdef __cplusplus +template +uint8_t* serialize(uint8_t* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) { + size_t size = sizeof(T); + uint8_t* pDst = buf; + uint8_t* pSrc = (uint8_t*)&value; + + if (host_endian == buf_endian) { + memcpy(pDst, pSrc, size); + } + else { + for (int i = 0; i < size; ++i) { + pDst[i] = pSrc[size-i-1]; + } + } + + return buf+size; +} + +template +uint8_t* deserialize(uint8_t* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) { + size_t size = sizeof(T); + uint8_t* pSrc = buf; + uint8_t* pDst = (uint8_t*)value; + + if (host_endian == buf_endian) { + memcpy(pDst, pSrc, size); + } + else { + for (int i = 0; i < size; ++i) { + pDst[i] = pSrc[size-i-1]; + } + } + + return buf+size; +} +#endif // __cplusplus + +#endif // HV_ENDIAN_H_ diff --git a/external/libhv/libhv-1.3.2/base/herr.c b/external/libhv/libhv-1.3.2/base/herr.c new file mode 100644 index 0000000..d3adf16 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/herr.c @@ -0,0 +1,19 @@ +#include "herr.h" + +#include // for strerror + +// errcode => errmsg +const char* hv_strerror(int err) { + if (err > 0 && err <= SYS_NERR) { + return strerror(err); + } + + switch (err) { +#define F(errcode, name, errmsg) \ + case errcode: return errmsg; + FOREACH_ERR(F) +#undef F + default: + return "Undefined error"; + } +} diff --git a/external/libhv/libhv-1.3.2/base/herr.h b/external/libhv/libhv-1.3.2/base/herr.h new file mode 100644 index 0000000..adb6d07 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/herr.h @@ -0,0 +1,122 @@ +#ifndef HV_ERR_H_ +#define HV_ERR_H_ + +#include + +#include "hexport.h" + +#ifndef SYS_NERR +#define SYS_NERR 133 +#endif + +// F(errcode, name, errmsg) +// [1, 133] +#define FOREACH_ERR_SYS(F) + +// [1xx~5xx] +#define FOREACH_ERR_STATUS(F) + +// [1xxx] +#define FOREACH_ERR_COMMON(F) \ + F(0, OK, "OK") \ + F(1000, UNKNOWN, "Unknown error") \ + \ + F(1001, NULL_PARAM, "Null parameter") \ + F(1002, NULL_POINTER, "Null pointer") \ + F(1003, NULL_DATA, "Null data") \ + F(1004, NULL_HANDLE, "Null handle") \ + \ + F(1011, INVALID_PARAM, "Invalid parameter")\ + F(1012, INVALID_POINTER, "Invalid pointer") \ + F(1013, INVALID_DATA, "Invalid data") \ + F(1014, INVALID_HANDLE, "Invalid handle") \ + F(1015, INVALID_JSON, "Invalid json") \ + F(1016, INVALID_XML, "Invalid xml") \ + F(1017, INVALID_FMT, "Invalid format") \ + F(1018, INVALID_PROTOCOL, "Invalid protocol") \ + F(1019, INVALID_PACKAGE, "Invalid package") \ + \ + F(1021, OUT_OF_RANGE, "Out of range") \ + F(1022, OVER_LIMIT, "Over the limit") \ + F(1023, MISMATCH, "Mismatch") \ + F(1024, PARSE, "Parse failed") \ + \ + F(1030, OPEN_FILE, "Open file failed") \ + F(1031, SAVE_FILE, "Save file failed") \ + F(1032, READ_FILE, "Read file failed") \ + F(1033, WRITE_FILE, "Write file failed")\ + \ + F(1040, SSL, "SSL/TLS error") \ + F(1041, NEW_SSL_CTX, "New SSL_CTX failed") \ + F(1042, NEW_SSL, "New SSL failed") \ + F(1043, SSL_HANDSHAKE, "SSL handshake failed") \ + \ + F(1100, TASK_TIMEOUT, "Task timeout") \ + F(1101, TASK_QUEUE_FULL, "Task queue full") \ + F(1102, TASK_QUEUE_EMPTY, "Task queue empty") \ + \ + F(1400, REQUEST, "Bad request") \ + F(1401, RESPONSE, "Bad response") \ + +// [-1xxx] +#define FOREACH_ERR_FUNC(F) \ + F(-1001, MALLOC, "malloc() error") \ + F(-1002, REALLOC, "realloc() error") \ + F(-1003, CALLOC, "calloc() error") \ + F(-1004, FREE, "free() error") \ + \ + F(-1011, SOCKET, "socket() error") \ + F(-1012, BIND, "bind() error") \ + F(-1013, LISTEN, "listen() error") \ + F(-1014, ACCEPT, "accept() error") \ + F(-1015, CONNECT, "connect() error") \ + F(-1016, RECV, "recv() error") \ + F(-1017, SEND, "send() error") \ + F(-1018, RECVFROM, "recvfrom() error") \ + F(-1019, SENDTO, "sendto() error") \ + F(-1020, SETSOCKOPT, "setsockopt() error") \ + F(-1021, GETSOCKOPT, "getsockopt() error") \ + +// grpc [4xxx] +#define FOREACH_ERR_GRPC(F) \ + F(4000, GRPC_FIRST, "grpc no error") \ + F(4001, GRPC_STATUS_CANCELLED, "grpc status: cancelled") \ + F(4002, GRPC_STATUS_UNKNOWN, "grpc unknown error") \ + F(4003, GRPC_STATUS_INVALID_ARGUMENT, "grpc status: invalid argument")\ + F(4004, GRPC_STATUS_DEADLINE, "grpc status: deadline") \ + F(4005, GRPC_STATUS_NOT_FOUND, "grpc status: not found") \ + F(4006, GRPC_STATUS_ALREADY_EXISTS, "grpc status: already exists") \ + F(4007, GRPC_STATUS_PERMISSION_DENIED, "grpc status: permission denied") \ + F(4008, GRPC_STATUS_RESOURCE_EXHAUSTED, "grpc status: resource exhausted") \ + F(4009, GRPC_STATUS_FAILED_PRECONDITION,"grpc status: failed precondition") \ + F(4010, GRPC_STATUS_ABORTED, "grpc status: aborted") \ + F(4011, GRPC_STATUS_OUT_OF_RANGE, "grpc status: out of range") \ + F(4012, GRPC_STATUS_UNIMPLEMENTED, "grpc status: unimplemented") \ + F(4013, GRPC_STATUS_INTERNAL, "grpc internal error") \ + F(4014, GRPC_STATUS_UNAVAILABLE, "grpc service unavailable") \ + F(4015, GRPC_STATUS_DATA_LOSS, "grpc status: data loss") \ + +#define FOREACH_ERR(F) \ + FOREACH_ERR_COMMON(F) \ + FOREACH_ERR_FUNC(F) \ + FOREACH_ERR_GRPC(F) \ + +#undef ERR_OK // prevent conflict +enum { +#define F(errcode, name, errmsg) ERR_##name = errcode, + FOREACH_ERR(F) +#undef F +}; + +#ifdef __cplusplus +extern "C" { +#endif + +// errcode => errmsg +HV_EXPORT const char* hv_strerror(int err); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // HV_ERR_H_ diff --git a/external/libhv/libhv-1.3.2/base/hlog.c b/external/libhv/libhv-1.3.2/base/hlog.c new file mode 100644 index 0000000..2992dd8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hlog.c @@ -0,0 +1,463 @@ +#include "hlog.h" + +#include +#include +#include +#include +#include + +//#include "hmutex.h" +#ifdef _WIN32 +#pragma warning (disable: 4244) // conversion loss of data +#include +#define hmutex_t CRITICAL_SECTION +#define hmutex_init InitializeCriticalSection +#define hmutex_destroy DeleteCriticalSection +#define hmutex_lock EnterCriticalSection +#define hmutex_unlock LeaveCriticalSection +#else +#include // for gettimeofday +#include +#define hmutex_t pthread_mutex_t +#define hmutex_init(mutex) pthread_mutex_init(mutex, NULL) +#define hmutex_destroy pthread_mutex_destroy +#define hmutex_lock pthread_mutex_lock +#define hmutex_unlock pthread_mutex_unlock +#endif + +//#include "htime.h" +#define SECONDS_PER_HOUR 3600 +#define SECONDS_PER_DAY 86400 // 24*3600 +#define SECONDS_PER_WEEK 604800 // 7*24*3600; + +static int s_gmtoff = 28800; // 8*3600 + +struct logger_s { + logger_handler handler; + unsigned int bufsize; + char* buf; + + int level; + int enable_color; + char format[64]; + + // for file logger + char filepath[256]; + unsigned long long max_filesize; + int remain_days; + int enable_fsync; + FILE* fp_; + char cur_logfile[256]; + time_t last_logfile_ts; + int can_write_cnt; + + hmutex_t mutex_; // thread-safe +}; + +static void logger_init(logger_t* logger) { + logger->handler = NULL; + logger->bufsize = DEFAULT_LOG_MAX_BUFSIZE; + logger->buf = (char*)malloc(logger->bufsize); + + logger->level = DEFAULT_LOG_LEVEL; + logger->enable_color = 0; + // NOTE: format is faster 6% than snprintf + // logger->format[0] = '\0'; + strncpy(logger->format, DEFAULT_LOG_FORMAT, sizeof(logger->format) - 1); + + logger->fp_ = NULL; + logger->max_filesize = DEFAULT_LOG_MAX_FILESIZE; + logger->remain_days = DEFAULT_LOG_REMAIN_DAYS; + logger->enable_fsync = 1; + logger_set_file(logger, DEFAULT_LOG_FILE); + logger->last_logfile_ts = 0; + logger->can_write_cnt = -1; + hmutex_init(&logger->mutex_); +} + +logger_t* logger_create() { + // init gmtoff here + time_t ts = time(NULL); + struct tm* local_tm = localtime(&ts); + int local_hour = local_tm->tm_hour; + struct tm* gmt_tm = gmtime(&ts); + int gmt_hour = gmt_tm->tm_hour; + s_gmtoff = (local_hour - gmt_hour) * SECONDS_PER_HOUR; + + logger_t* logger = (logger_t*)malloc(sizeof(logger_t)); + logger_init(logger); + return logger; +} + +void logger_destroy(logger_t* logger) { + if (logger) { + if (logger->buf) { + free(logger->buf); + logger->buf = NULL; + } + if (logger->fp_) { + fclose(logger->fp_); + logger->fp_ = NULL; + } + hmutex_destroy(&logger->mutex_); + free(logger); + } +} + +void logger_set_handler(logger_t* logger, logger_handler fn) { + logger->handler = fn; +} + +void logger_set_level(logger_t* logger, int level) { + logger->level = level; +} + +void logger_set_level_by_str(logger_t* logger, const char* szLoglevel) { + int loglevel = DEFAULT_LOG_LEVEL; + if (strcmp(szLoglevel, "VERBOSE") == 0) { + loglevel = LOG_LEVEL_VERBOSE; + } else if (strcmp(szLoglevel, "DEBUG") == 0) { + loglevel = LOG_LEVEL_DEBUG; + } else if (strcmp(szLoglevel, "INFO") == 0) { + loglevel = LOG_LEVEL_INFO; + } else if (strcmp(szLoglevel, "WARN") == 0) { + loglevel = LOG_LEVEL_WARN; + } else if (strcmp(szLoglevel, "ERROR") == 0) { + loglevel = LOG_LEVEL_ERROR; + } else if (strcmp(szLoglevel, "FATAL") == 0) { + loglevel = LOG_LEVEL_FATAL; + } else if (strcmp(szLoglevel, "SILENT") == 0) { + loglevel = LOG_LEVEL_SILENT; + } else { + loglevel = DEFAULT_LOG_LEVEL; + } + logger->level = loglevel; +} + +void logger_set_format(logger_t* logger, const char* format) { + if (format) { + strncpy(logger->format, format, sizeof(logger->format) - 1); + } else { + logger->format[0] = '\0'; + } +} + +void logger_set_remain_days(logger_t* logger, int days) { + logger->remain_days = days; +} + +void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize) { + logger->bufsize = bufsize; + logger->buf = (char*)realloc(logger->buf, bufsize); +} + +void logger_enable_color(logger_t* logger, int on) { + logger->enable_color = on; +} + +void logger_set_file(logger_t* logger, const char* filepath) { + strncpy(logger->filepath, filepath, sizeof(logger->filepath) - 1); + // remove suffix .log + char* suffix = strrchr(logger->filepath, '.'); + if (suffix && strcmp(suffix, ".log") == 0) { + *suffix = '\0'; + } +} + +void logger_set_max_filesize(logger_t* logger, unsigned long long filesize) { + logger->max_filesize = filesize; +} + +void logger_set_max_filesize_by_str(logger_t* logger, const char* str) { + int num = atoi(str); + if (num <= 0) return; + // 16 16M 16MB + const char* e = str; + while (*e != '\0') ++e; + --e; + char unit; + if (*e >= '0' && *e <= '9') unit = 'M'; + else if (*e == 'B') unit = *(e-1); + else unit = *e; + unsigned long long filesize = num; + switch (unit) { + case 'K': filesize <<= 10; break; + case 'M': filesize <<= 20; break; + case 'G': filesize <<= 30; break; + default: filesize <<= 20; break; + } + logger->max_filesize = filesize; +} + +void logger_enable_fsync(logger_t* logger, int on) { + logger->enable_fsync = on; +} + +void logger_fsync(logger_t* logger) { + hmutex_lock(&logger->mutex_); + if (logger->fp_) { + fflush(logger->fp_); + } + hmutex_unlock(&logger->mutex_); +} + +const char* logger_get_cur_file(logger_t* logger) { + return logger->cur_logfile; +} + +static void logfile_name(const char* filepath, time_t ts, char* buf, int len) { + struct tm* tm = localtime(&ts); + snprintf(buf, len, "%s.%04d%02d%02d.log", + filepath, + tm->tm_year+1900, + tm->tm_mon+1, + tm->tm_mday); +} + +static FILE* logfile_shift(logger_t* logger) { + time_t ts_now = time(NULL); + int interval_days = logger->last_logfile_ts == 0 ? 0 : (ts_now+s_gmtoff) / SECONDS_PER_DAY - (logger->last_logfile_ts+s_gmtoff) / SECONDS_PER_DAY; + if (logger->fp_ == NULL || interval_days > 0) { + // close old logfile + if (logger->fp_) { + fclose(logger->fp_); + logger->fp_ = NULL; + } + else { + interval_days = 30; + } + + if (logger->remain_days >= 0) { + char rm_logfile[256] = {0}; + if (interval_days >= logger->remain_days) { + // remove [today-interval_days, today-remain_days] logfile + for (int i = interval_days; i >= logger->remain_days; --i) { + time_t ts_rm = ts_now - i * SECONDS_PER_DAY; + logfile_name(logger->filepath, ts_rm, rm_logfile, sizeof(rm_logfile)); + remove(rm_logfile); + } + } + else { + // remove today-remain_days logfile + time_t ts_rm = ts_now - logger->remain_days * SECONDS_PER_DAY; + logfile_name(logger->filepath, ts_rm, rm_logfile, sizeof(rm_logfile)); + remove(rm_logfile); + } + } + } + + // open today logfile + if (logger->fp_ == NULL) { + logfile_name(logger->filepath, ts_now, logger->cur_logfile, sizeof(logger->cur_logfile)); + logger->fp_ = fopen(logger->cur_logfile, "a"); + logger->last_logfile_ts = ts_now; + } + + // NOTE: estimate can_write_cnt to avoid frequent fseek/ftell + if (logger->fp_ && --logger->can_write_cnt < 0) { + fseek(logger->fp_, 0, SEEK_END); + long filesize = ftell(logger->fp_); + if (filesize > logger->max_filesize) { + fclose(logger->fp_); + logger->fp_ = NULL; + // ftruncate + logger->fp_ = fopen(logger->cur_logfile, "w"); + // reopen with O_APPEND for multi-processes + if (logger->fp_) { + fclose(logger->fp_); + logger->fp_ = fopen(logger->cur_logfile, "a"); + } + } + else { + logger->can_write_cnt = (logger->max_filesize - filesize) / logger->bufsize; + } + } + + return logger->fp_; +} + +static void logfile_write(logger_t* logger, const char* buf, int len) { + FILE* fp = logfile_shift(logger); + if (fp) { + fwrite(buf, 1, len, fp); + if (logger->enable_fsync) { + fflush(fp); + } + } +} + +static int i2a(int i, char* buf, int len) { + for (int l = len - 1; l >= 0; --l) { + if (i == 0) { + buf[l] = '0'; + } else { + buf[l] = i % 10 + '0'; + i /= 10; + } + } + return len; +} + +int logger_print(logger_t* logger, int level, const char* fmt, ...) { + if (level < logger->level) + return -10; + + int year,month,day,hour,min,sec,us; +#ifdef _WIN32 + SYSTEMTIME tm; + GetLocalTime(&tm); + year = tm.wYear; + month = tm.wMonth; + day = tm.wDay; + hour = tm.wHour; + min = tm.wMinute; + sec = tm.wSecond; + us = tm.wMilliseconds * 1000; +#else + struct timeval tv; + struct tm* tm = NULL; + gettimeofday(&tv, NULL); + time_t tt = tv.tv_sec; + tm = localtime(&tt); + year = tm->tm_year + 1900; + month = tm->tm_mon + 1; + day = tm->tm_mday; + hour = tm->tm_hour; + min = tm->tm_min; + sec = tm->tm_sec; + us = tv.tv_usec; +#endif + + const char* pcolor = ""; + const char* plevel = ""; +#define XXX(id, str, clr) \ + case id: plevel = str; pcolor = clr; break; + + switch (level) { + LOG_LEVEL_MAP(XXX) + } +#undef XXX + + // lock logger->buf + hmutex_lock(&logger->mutex_); + + char* buf = logger->buf; + int bufsize = logger->bufsize; + int len = 0; + + if (logger->enable_color) { + len = snprintf(buf, bufsize, "%s", pcolor); + } + + const char* p = logger->format; + if (*p) { + while (*p) { + if (*p == '%') { + switch(*++p) { + case 'y': + len += i2a(year, buf + len, 4); + break; + case 'm': + len += i2a(month, buf + len, 2); + break; + case 'd': + len += i2a(day, buf + len, 2); + break; + case 'H': + len += i2a(hour, buf + len, 2); + break; + case 'M': + len += i2a(min, buf + len, 2); + break; + case 'S': + len += i2a(sec, buf + len, 2); + break; + case 'z': + len += i2a(us/1000, buf + len, 3); + break; + case 'Z': + len += i2a(us, buf + len, 6); + break; + case 'l': + buf[len++] = *plevel; + break; + case 'L': + for (int i = 0; i < 5; ++i) { + buf[len++] = plevel[i]; + } + break; + case 's': + { + va_list ap; + va_start(ap, fmt); + len += vsnprintf(buf + len, bufsize - len, fmt, ap); + va_end(ap); + } + break; + case '%': + buf[len++] = '%'; + break; + default: break; + } + } else { + buf[len++] = *p; + } + ++p; + } + } else { + len += snprintf(buf + len, bufsize - len, "%04d-%02d-%02d %02d:%02d:%02d.%03d %s ", + year, month, day, hour, min, sec, us/1000, + plevel); + + va_list ap; + va_start(ap, fmt); + len += vsnprintf(buf + len, bufsize - len, fmt, ap); + va_end(ap); + } + + if (logger->enable_color) { + len += snprintf(buf + len, bufsize - len, "%s", CLR_CLR); + } + + if(lenhandler) { + logger->handler(level, buf, len); + } + else { + logfile_write(logger, buf, len); + } + + hmutex_unlock(&logger->mutex_); + return len; +} + +static logger_t* s_logger = NULL; +logger_t* hv_default_logger() { + if (s_logger == NULL) { + s_logger = logger_create(); + atexit(hv_destroy_default_logger); + } + return s_logger; +} +void hv_destroy_default_logger(void) { + if (s_logger) { + logger_fsync(s_logger); + logger_destroy(s_logger); + s_logger = NULL; + } +} + +void stdout_logger(int loglevel, const char* buf, int len) { + fprintf(stdout, "%.*s", len, buf); +} + +void stderr_logger(int loglevel, const char* buf, int len) { + fprintf(stderr, "%.*s", len, buf); +} + +void file_logger(int loglevel, const char* buf, int len) { + logfile_write(hv_default_logger(), buf, len); +} diff --git a/external/libhv/libhv-1.3.2/base/hlog.h b/external/libhv/libhv-1.3.2/base/hlog.h new file mode 100644 index 0000000..5836b90 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hlog.h @@ -0,0 +1,176 @@ +#ifndef HV_LOG_H_ +#define HV_LOG_H_ + +/* + * hlog is thread-safe + */ + +#include + +#ifdef _WIN32 +#define DIR_SEPARATOR '\\' +#define DIR_SEPARATOR_STR "\\" +#else +#define DIR_SEPARATOR '/' +#define DIR_SEPARATOR_STR "/" +#endif + +#ifndef __FILENAME__ +// #define __FILENAME__ (strrchr(__FILE__, DIR_SEPARATOR) ? strrchr(__FILE__, DIR_SEPARATOR) + 1 : __FILE__) +#define __FILENAME__ (strrchr(DIR_SEPARATOR_STR __FILE__, DIR_SEPARATOR) + 1) +#endif + +#include "hexport.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define CLR_CLR "\033[0m" /* 恢复颜色 */ +#define CLR_BLACK "\033[30m" /* 黑色字 */ +#define CLR_RED "\033[31m" /* 红色字 */ +#define CLR_GREEN "\033[32m" /* 绿色字 */ +#define CLR_YELLOW "\033[33m" /* 黄色字 */ +#define CLR_BLUE "\033[34m" /* 蓝色字 */ +#define CLR_PURPLE "\033[35m" /* 紫色字 */ +#define CLR_SKYBLUE "\033[36m" /* 天蓝字 */ +#define CLR_WHITE "\033[37m" /* 白色字 */ + +#define CLR_BLK_WHT "\033[40;37m" /* 黑底白字 */ +#define CLR_RED_WHT "\033[41;37m" /* 红底白字 */ +#define CLR_GREEN_WHT "\033[42;37m" /* 绿底白字 */ +#define CLR_YELLOW_WHT "\033[43;37m" /* 黄底白字 */ +#define CLR_BLUE_WHT "\033[44;37m" /* 蓝底白字 */ +#define CLR_PURPLE_WHT "\033[45;37m" /* 紫底白字 */ +#define CLR_SKYBLUE_WHT "\033[46;37m" /* 天蓝底白字 */ +#define CLR_WHT_BLK "\033[47;30m" /* 白底黑字 */ + +// XXX(id, str, clr) +#define LOG_LEVEL_MAP(XXX) \ + XXX(LOG_LEVEL_DEBUG, "DEBUG", CLR_WHITE) \ + XXX(LOG_LEVEL_INFO, "INFO ", CLR_GREEN) \ + XXX(LOG_LEVEL_WARN, "WARN ", CLR_YELLOW) \ + XXX(LOG_LEVEL_ERROR, "ERROR", CLR_RED) \ + XXX(LOG_LEVEL_FATAL, "FATAL", CLR_RED_WHT) + +typedef enum { + LOG_LEVEL_VERBOSE = 0, +#define XXX(id, str, clr) id, + LOG_LEVEL_MAP(XXX) +#undef XXX + LOG_LEVEL_SILENT +} log_level_e; + +#define DEFAULT_LOG_FILE "libhv" +#define DEFAULT_LOG_LEVEL LOG_LEVEL_INFO +#define DEFAULT_LOG_FORMAT "%y-%m-%d %H:%M:%S.%z %L %s" +#define DEFAULT_LOG_REMAIN_DAYS 1 +#define DEFAULT_LOG_MAX_BUFSIZE (1<<14) // 16k +#define DEFAULT_LOG_MAX_FILESIZE (1<<24) // 16M + +// logger: default file_logger +// network_logger() see event/nlog.h +typedef void (*logger_handler)(int loglevel, const char* buf, int len); + +HV_EXPORT void stdout_logger(int loglevel, const char* buf, int len); +HV_EXPORT void stderr_logger(int loglevel, const char* buf, int len); +HV_EXPORT void file_logger(int loglevel, const char* buf, int len); +// network_logger implement see event/nlog.h +// HV_EXPORT void network_logger(int loglevel, const char* buf, int len); + +typedef struct logger_s logger_t; +HV_EXPORT logger_t* logger_create(); +HV_EXPORT void logger_destroy(logger_t* logger); + +HV_EXPORT void logger_set_handler(logger_t* logger, logger_handler fn); +HV_EXPORT void logger_set_level(logger_t* logger, int level); +// level = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] +HV_EXPORT void logger_set_level_by_str(logger_t* logger, const char* level); +/* + * format = "%y-%m-%d %H:%M:%S.%z %L %s" + * message = "2020-01-02 03:04:05.067 DEBUG message" + * %y year + * %m month + * %d day + * %H hour + * %M min + * %S sec + * %z ms + * %Z us + * %l First character of level + * %L All characters of level + * %s message + * %% % + */ +HV_EXPORT void logger_set_format(logger_t* logger, const char* format); +HV_EXPORT void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize); +HV_EXPORT void logger_enable_color(logger_t* logger, int on); +HV_EXPORT int logger_print(logger_t* logger, int level, const char* fmt, ...); + +// below for file logger +HV_EXPORT void logger_set_file(logger_t* logger, const char* filepath); +HV_EXPORT void logger_set_max_filesize(logger_t* logger, unsigned long long filesize); +// 16, 16M, 16MB +HV_EXPORT void logger_set_max_filesize_by_str(logger_t* logger, const char* filesize); +HV_EXPORT void logger_set_remain_days(logger_t* logger, int days); +HV_EXPORT void logger_enable_fsync(logger_t* logger, int on); +HV_EXPORT void logger_fsync(logger_t* logger); +HV_EXPORT const char* logger_get_cur_file(logger_t* logger); + +// hlog: default logger instance +HV_EXPORT logger_t* hv_default_logger(); +HV_EXPORT void hv_destroy_default_logger(void); + +// macro hlog* +#define hlog hv_default_logger() +#define hlog_destory() hv_destroy_default_logger() +#define hlog_disable() logger_set_level(hlog, LOG_LEVEL_SILENT) +#define hlog_set_file(filepath) logger_set_file(hlog, filepath) +#define hlog_set_level(level) logger_set_level(hlog, level) +#define hlog_set_level_by_str(level) logger_set_level_by_str(hlog, level) +#define hlog_set_handler(fn) logger_set_handler(hlog, fn) +#define hlog_set_format(format) logger_set_format(hlog, format) +#define hlog_set_max_filesize(filesize) logger_set_max_filesize(hlog, filesize) +#define hlog_set_max_filesize_by_str(filesize) logger_set_max_filesize_by_str(hlog, filesize) +#define hlog_set_remain_days(days) logger_set_remain_days(hlog, days) +#define hlog_enable_fsync() logger_enable_fsync(hlog, 1) +#define hlog_disable_fsync() logger_enable_fsync(hlog, 0) +#define hlog_fsync() logger_fsync(hlog) +#define hlog_get_cur_file() logger_get_cur_file(hlog) + +#define hlogd(fmt, ...) logger_print(hlog, LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogi(fmt, ...) logger_print(hlog, LOG_LEVEL_INFO, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogw(fmt, ...) logger_print(hlog, LOG_LEVEL_WARN, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hloge(fmt, ...) logger_print(hlog, LOG_LEVEL_ERROR, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogf(fmt, ...) logger_print(hlog, LOG_LEVEL_FATAL, fmt " [%s:%d:%s]", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) + +// below for android +#if defined(ANDROID) || defined(__ANDROID__) +#include +#define LOG_TAG "JNI" +#undef hlogd +#undef hlogi +#undef hlogw +#undef hloge +#undef hlogf +#define hlogd(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) +#define hlogi(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) +#define hlogw(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) +#define hloge(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) +#define hlogf(...) __android_log_print(ANDROID_LOG_FATAL, LOG_TAG, __VA_ARGS__) +#endif + +// macro alias +#if !defined(LOGD) && !defined(LOGI) && !defined(LOGW) && !defined(LOGE) && !defined(LOGF) +#define LOGD hlogd +#define LOGI hlogi +#define LOGW hlogw +#define LOGE hloge +#define LOGF hlogf +#endif + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // HV_LOG_H_ diff --git a/external/libhv/libhv-1.3.2/base/hmain.c b/external/libhv/libhv-1.3.2/base/hmain.c new file mode 100644 index 0000000..41398a5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hmain.c @@ -0,0 +1,674 @@ +#include "hmain.h" + +#include "hbase.h" +#include "hlog.h" +#include "herr.h" +#include "htime.h" +#include "hthread.h" + +#ifdef OS_DARWIN +#include +#define environ (*_NSGetEnviron()) +#endif + +main_ctx_t g_main_ctx; + +static void init_arg_kv(int maxsize) { + g_main_ctx.arg_kv_size = 0; + SAFE_ALLOC(g_main_ctx.arg_kv, sizeof(char*) * maxsize); +} + +static void save_arg_kv(const char* key, int key_len, const char* val, int val_len) { + if (key_len <= 0) key_len = strlen(key); + if (val_len <= 0) val_len = strlen(val); + char* arg = NULL; + SAFE_ALLOC(arg, key_len + val_len + 2); + memcpy(arg, key, key_len); + arg[key_len] = '='; + memcpy(arg + key_len + 1, val, val_len); + // printf("save_arg_kv: %s\n", arg); + g_main_ctx.arg_kv[g_main_ctx.arg_kv_size++] = arg; +} + +static void init_arg_list(int maxsize) { + g_main_ctx.arg_list_size = 0; + SAFE_ALLOC(g_main_ctx.arg_list, sizeof(char*) * maxsize); +} + +static void save_arg_list(const char* arg) { + // printf("save_arg_list: %s\n", arg); + g_main_ctx.arg_list[g_main_ctx.arg_list_size++] = strdup(arg); +} + +static const char* get_val(char** kvs, const char* key) { + if (kvs == NULL) return NULL; + int key_len = strlen(key); + char* kv = NULL; + int kv_len = 0; + for (int i = 0; kvs[i]; ++i) { + kv = kvs[i]; + kv_len = strlen(kv); + if (kv_len <= key_len) continue; + // key=val + if (memcmp(kv, key, key_len) == 0 && kv[key_len] == '=') { + return kv + key_len + 1; + } + } + return NULL; +} + +const char* get_arg(const char* key) { + return get_val(g_main_ctx.arg_kv, key); +} + +const char* get_env(const char* key) { + return get_val(g_main_ctx.save_envp, key); +} + +int main_ctx_init(int argc, char** argv) { + if (argc == 0 || argv == NULL) { + argc = 1; + SAFE_ALLOC(argv, 2 * sizeof(char*)); + SAFE_ALLOC(argv[0], MAX_PATH); + get_executable_path(argv[0], MAX_PATH); + } + + get_run_dir(g_main_ctx.run_dir, sizeof(g_main_ctx.run_dir)); + //printf("run_dir=%s\n", g_main_ctx.run_dir); + strncpy(g_main_ctx.program_name, hv_basename(argv[0]), sizeof(g_main_ctx.program_name)); +#ifdef OS_WIN + if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) { + *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0'; + } +#endif + //printf("program_name=%s\n", g_main_ctx.program_name); + char logdir[MAX_PATH] = {0}; + snprintf(logdir, sizeof(logdir), "%s/logs", g_main_ctx.run_dir); + hv_mkdir(logdir); + snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_dir, g_main_ctx.program_name); + snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_dir, g_main_ctx.program_name); + snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.logfile), "%s/logs/%s.log", g_main_ctx.run_dir, g_main_ctx.program_name); + hlog_set_file(g_main_ctx.logfile); + + g_main_ctx.pid = getpid(); + g_main_ctx.oldpid = getpid_from_pidfile(); +#ifdef OS_UNIX + if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) { + g_main_ctx.oldpid = -1; + } +#else + HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, g_main_ctx.oldpid); + if (hproc == NULL) { + g_main_ctx.oldpid = -1; + } + else { + CloseHandle(hproc); + } +#endif + + // save arg + int i = 0; + g_main_ctx.os_argv = argv; + g_main_ctx.argc = 0; + g_main_ctx.arg_len = 0; + for (i = 0; argv[i]; ++i) { + g_main_ctx.arg_len += strlen(argv[i]) + 1; + } + g_main_ctx.argc = i; + char* argp = NULL; + SAFE_ALLOC(argp, g_main_ctx.arg_len); + SAFE_ALLOC(g_main_ctx.save_argv, (g_main_ctx.argc + 1) * sizeof(char*)); + char* cmdline = NULL; + SAFE_ALLOC(cmdline, g_main_ctx.arg_len); + g_main_ctx.cmdline = cmdline; + for (i = 0; argv[i]; ++i) { + strcpy(argp, argv[i]); + g_main_ctx.save_argv[i] = argp; + argp += strlen(argv[i]) + 1; + + strcpy(cmdline, argv[i]); + cmdline += strlen(argv[i]); + *cmdline = ' '; + ++cmdline; + } + g_main_ctx.save_argv[g_main_ctx.argc] = NULL; + g_main_ctx.cmdline[g_main_ctx.arg_len-1] = '\0'; + +#if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_DARWIN) + // save env + g_main_ctx.os_envp = environ; + g_main_ctx.envc = 0; + g_main_ctx.env_len = 0; + for (i = 0; environ[i]; ++i) { + g_main_ctx.env_len += strlen(environ[i]) + 1; + } + g_main_ctx.envc = i; + char* envp = NULL; + SAFE_ALLOC(envp, g_main_ctx.env_len); + SAFE_ALLOC(g_main_ctx.save_envp, (g_main_ctx.envc + 1) * sizeof(char*)); + for (i = 0; environ[i]; ++i) { + g_main_ctx.save_envp[i] = envp; + strcpy(g_main_ctx.save_envp[i], environ[i]); + envp += strlen(environ[i]) + 1; + } + g_main_ctx.save_envp[g_main_ctx.envc] = NULL; +#endif + + // signals + g_main_ctx.reload_fn = NULL; + g_main_ctx.reload_userdata = NULL; + + // master workers + g_main_ctx.worker_processes = 0; + g_main_ctx.worker_threads = 0; + g_main_ctx.worker_fn = 0; + g_main_ctx.worker_userdata = 0; + g_main_ctx.proc_ctxs = NULL; + + atexit(main_ctx_free); + return 0; +} + +void main_ctx_free(void) { + if (g_main_ctx.save_argv) { + SAFE_FREE(g_main_ctx.save_argv[0]); + SAFE_FREE(g_main_ctx.save_argv); + } + SAFE_FREE(g_main_ctx.cmdline); + if (g_main_ctx.save_envp) { + SAFE_FREE(g_main_ctx.save_envp[0]); + SAFE_FREE(g_main_ctx.save_envp); + } + if (g_main_ctx.arg_kv) { + for (int i = 0; i < g_main_ctx.arg_kv_size; ++i) { + SAFE_FREE(g_main_ctx.arg_kv[i]); + } + SAFE_FREE(g_main_ctx.arg_kv); + } + if (g_main_ctx.arg_list) { + for (int i = 0; i < g_main_ctx.arg_list_size; ++i) { + SAFE_FREE(g_main_ctx.arg_list[i]); + } + SAFE_FREE(g_main_ctx.arg_list); + } +} + +#define UNDEFINED_OPTION -1 +static int get_arg_type(int short_opt, const char* options) { + if (options == NULL) return UNDEFINED_OPTION; + const char* p = options; + while (*p && *p != short_opt) ++p; + if (*p == '\0') return UNDEFINED_OPTION; + if (*(p+1) == ':') return REQUIRED_ARGUMENT; + return NO_ARGUMENT; +} + +int parse_opt(int argc, char** argv, const char* options) { + if (argc < 1) return 0; + init_arg_kv(strlen(options) + 1); + init_arg_list(argc); + + for (int i = 1; argv[i]; ++i) { + char* p = argv[i]; + if (*p != '-') { + save_arg_list(argv[i]); + continue; + } + while (*++p) { + int arg_type = get_arg_type(*p, options); + if (arg_type == UNDEFINED_OPTION) { + printf("Invalid option '%c'\n", *p); + return -20; + } else if (arg_type == NO_ARGUMENT) { + save_arg_kv(p, 1, OPTION_ENABLE, 0); + continue; + } else if (arg_type == REQUIRED_ARGUMENT) { + if (*(p+1) != '\0') { + save_arg_kv(p, 1, p+1, 0); + break; + } else if (argv[i+1] != NULL) { + save_arg_kv(p, 1, argv[++i], 0); + break; + } else { + printf("Option '%c' requires param\n", *p); + return -30; + } + } + } + } + return 0; +} + +static const option_t* get_option(const char* opt, const option_t* long_options, int size) { + if (opt == NULL || long_options == NULL) return NULL; + int len = strlen(opt); + if (len == 0) return NULL; + if (len == 1) { + for (int i = 0; i < size; ++i) { + if (long_options[i].short_opt == *opt) { + return &long_options[i]; + } + } + } else { + for (int i = 0; i < size; ++i) { + if (strcmp(long_options[i].long_opt, opt) == 0) { + return &long_options[i]; + } + } + } + + return NULL; +} + +#define MAX_OPTION 32 +// opt type +#define NOPREFIX_OPTION 0 +#define SHORT_OPTION -1 +#define LONG_OPTION -2 +int parse_opt_long(int argc, char** argv, const option_t* long_options, int size) { + if (argc < 1) return 0; + init_arg_kv(size + 1); + init_arg_list(argc); + + char opt[MAX_OPTION+1] = {0}; + for (int i = 1; argv[i]; ++i) { + char* arg = argv[i]; + int opt_type = NOPREFIX_OPTION; + // prefix + if (*arg == OPTION_PREFIX) { + ++arg; + opt_type = SHORT_OPTION; + if (*arg == OPTION_PREFIX) { + ++arg; + opt_type = LONG_OPTION; + } + } + int arg_len = strlen(arg); + // delim + char* delim = strchr(arg, OPTION_DELIM); + if (delim) { + if (delim == arg || delim == arg+arg_len-1 || delim-arg > MAX_OPTION) { + printf("Invalid option '%s'\n", argv[i]); + return -10; + } + memcpy(opt, arg, delim-arg); + opt[delim-arg] = '\0'; + } else { + if (opt_type == SHORT_OPTION) { + *opt = *arg; + opt[1] = '\0'; + } else { + strncpy(opt, arg, MAX_OPTION); + } + } + // get_option + const option_t* pOption = get_option(opt, long_options, size); + if (pOption == NULL) { + if (delim == NULL && opt_type == NOPREFIX_OPTION) { + save_arg_list(arg); + continue; + } else { + printf("Invalid option: '%s'\n", argv[i]); + return -10; + } + } + const char* value = NULL; + if (pOption->arg_type == NO_ARGUMENT) { + // -h + value = OPTION_ENABLE; + } else if (pOption->arg_type == REQUIRED_ARGUMENT) { + if (delim) { + // --port=80 + value = delim+1; + } else { + if (opt_type == SHORT_OPTION && *(arg+1) != '\0') { + // p80 + value = arg+1; + } else if (argv[i+1] != NULL) { + // --port 80 + value = argv[++i]; + } else { + printf("Option '%s' requires parament\n", opt); + return -20; + } + } + } + // preferred to use short_opt as key + if (pOption->short_opt > 0) { + save_arg_kv(&pOption->short_opt, 1, value, 0); + } else if (pOption->long_opt) { + save_arg_kv(pOption->long_opt, 0, value, 0); + } + } + return 0; +} + +#if defined(OS_UNIX) && !HAVE_SETPROCTITLE +/* + * memory layout + * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0 + */ +void setproctitle(const char* fmt, ...) { + char buf[256] = {0}; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf) - 1, fmt, ap); + va_end(ap); + + int len = g_main_ctx.arg_len + g_main_ctx.env_len; + if (g_main_ctx.os_argv && len) { + strncpy(g_main_ctx.os_argv[0], buf, len-1); + } +} +#endif + +int create_pidfile() { + FILE* fp = fopen(g_main_ctx.pidfile, "w"); + if (fp == NULL) { + hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno); + return -1; + } + + g_main_ctx.pid = hv_getpid(); + fprintf(fp, "%d\n", (int)g_main_ctx.pid); + fclose(fp); + hlogi("create_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid); + atexit(delete_pidfile); + return 0; +} + +void delete_pidfile(void) { + hlogi("delete_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid); + remove(g_main_ctx.pidfile); +} + +pid_t getpid_from_pidfile() { + FILE* fp = fopen(g_main_ctx.pidfile, "r"); + if (fp == NULL) { + // hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno); + return -1; + } + int pid = -1; + fscanf(fp, "%d", &pid); + fclose(fp); + return pid; +} + +#ifdef OS_UNIX +// unix use signal +#include + +void signal_handler(int signo) { + hlogi("pid=%d recv signo=%d", getpid(), signo); + switch (signo) { + case SIGINT: + case SIGNAL_TERMINATE: + hlogi("killall processes"); + signal(SIGCHLD, SIG_IGN); + // master send SIGKILL => workers + for (int i = 0; i < g_main_ctx.worker_processes; ++i) { + if (g_main_ctx.proc_ctxs[i].pid <= 0) break; + kill(g_main_ctx.proc_ctxs[i].pid, SIGKILL); + g_main_ctx.proc_ctxs[i].pid = -1; + } + exit(0); + break; + case SIGCHLD: + { + pid_t pid = 0; + int status = 0; + while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { + hlogw("proc stop/waiting, pid=%d status=%d", pid, status); + for (int i = 0; i < g_main_ctx.worker_processes; ++i) { + proc_ctx_t* ctx = g_main_ctx.proc_ctxs + i; + if (ctx->pid == pid) { + ctx->pid = -1; + // NOTE: avoid frequent crash and restart + time_t run_time = time(NULL) - ctx->start_time; + if (ctx->spawn_cnt < 3 || run_time > 3600) { + hproc_spawn(ctx); + } + else { + hloge("proc crash, pid=%d spawn_cnt=%d run_time=%us", + pid, ctx->spawn_cnt, (unsigned int)run_time); + + bool have_worker = false; + for (int i = 0; i < g_main_ctx.worker_processes; ++i) { + if (g_main_ctx.proc_ctxs[i].pid > 0) { + have_worker = true; + break; + } + } + if (!have_worker) { + hlogw("No alive worker process, exit master process!"); + exit(0); + } + } + break; + } + } + } + } + break; + case SIGNAL_RELOAD: + if (g_main_ctx.reload_fn) { + g_main_ctx.reload_fn(g_main_ctx.reload_userdata); + if (getpid_from_pidfile() == getpid()) { + // master send SIGNAL_RELOAD => workers + for (int i = 0; i < g_main_ctx.worker_processes; ++i) { + if (g_main_ctx.proc_ctxs[i].pid <= 0) break; + kill(g_main_ctx.proc_ctxs[i].pid, SIGNAL_RELOAD); + } + } + } + break; + default: + break; + } +} + +int signal_init(procedure_t reload_fn, void* reload_userdata) { + g_main_ctx.reload_fn = reload_fn; + g_main_ctx.reload_userdata = reload_userdata; + + signal(SIGINT, signal_handler); + signal(SIGCHLD, signal_handler); + signal(SIGNAL_TERMINATE, signal_handler); + signal(SIGNAL_RELOAD, signal_handler); + + return 0; +} + +#elif defined(OS_WIN) +#include // for timeSetEvent + +// win32 use Event +//static HANDLE s_hEventTerm = NULL; +static HANDLE s_hEventReload = NULL; + +static void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) { + DWORD ret; + /* + ret = WaitForSingleObject(s_hEventTerm, 0); + if (ret == WAIT_OBJECT_0) { + hlogi("pid=%d recv event [TERM]", getpid()); + if (getpid_from_pidfile() == getpid()) { + timeKillEvent(uTimerID); + exit(0); + } + } + */ + + ret = WaitForSingleObject(s_hEventReload, 0); + if (ret == WAIT_OBJECT_0) { + hlogi("pid=%d recv event [RELOAD]", getpid()); + if (g_main_ctx.reload_fn) { + g_main_ctx.reload_fn(g_main_ctx.reload_userdata); + } + } +} + +static void signal_cleanup(void) { + //CloseHandle(s_hEventTerm); + //s_hEventTerm = NULL; + CloseHandle(s_hEventReload); + s_hEventReload = NULL; +} + +int signal_init(procedure_t reload_fn, void* reload_userdata) { + g_main_ctx.reload_fn = reload_fn; + g_main_ctx.reload_userdata = reload_userdata; + + char eventname[MAX_PATH] = {0}; + //snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name); + //s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname); + //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname); + snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name); + s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname); + + timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC); + + atexit(signal_cleanup); + return 0; +} +#endif + +static void kill_proc(int pid) { +#ifdef OS_UNIX + kill(pid, SIGNAL_TERMINATE); +#else + //SetEvent(s_hEventTerm); + //hv_sleep(1); + HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid); + if (hproc) { + TerminateProcess(hproc, 0); + CloseHandle(hproc); + } +#endif +} + +void signal_handle(const char* signal) { + if (strcmp(signal, "start") == 0) { + if (g_main_ctx.oldpid > 0) { + printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid); + exit(0); + } + } else if (strcmp(signal, "stop") == 0) { + if (g_main_ctx.oldpid > 0) { + kill_proc(g_main_ctx.oldpid); + printf("%s stop/waiting\n", g_main_ctx.program_name); + } else { + printf("%s is already stopped\n", g_main_ctx.program_name); + } + exit(0); + } else if (strcmp(signal, "restart") == 0) { + if (g_main_ctx.oldpid > 0) { + kill_proc(g_main_ctx.oldpid); + printf("%s stop/waiting\n", g_main_ctx.program_name); + hv_sleep(1); + } + } else if (strcmp(signal, "status") == 0) { + if (g_main_ctx.oldpid > 0) { + printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid); + } else { + printf("%s stop/waiting\n", g_main_ctx.program_name); + } + exit(0); + } else if (strcmp(signal, "reload") == 0) { + if (g_main_ctx.oldpid > 0) { + printf("reload confile [%s]\n", g_main_ctx.confile); +#ifdef OS_UNIX + kill(g_main_ctx.oldpid, SIGNAL_RELOAD); +#else + SetEvent(s_hEventReload); +#endif + } + hv_sleep(1); + exit(0); + } else { + printf("Invalid signal: '%s'\n", signal); + exit(0); + } + printf("%s start/running\n", g_main_ctx.program_name); +} + +// master-workers processes +static HTHREAD_ROUTINE(worker_thread) { + hlogi("worker_thread pid=%ld tid=%ld", hv_getpid(), hv_gettid()); + if (g_main_ctx.worker_fn) { + g_main_ctx.worker_fn(g_main_ctx.worker_userdata); + } + return 0; +} + +static void worker_init(void* userdata) { +#ifdef OS_UNIX + setproctitle("%s: worker process", g_main_ctx.program_name); + signal(SIGNAL_RELOAD, signal_handler); +#endif +} + +static void worker_proc(void* userdata) { + for (int i = 1; i < g_main_ctx.worker_threads; ++i) { + hthread_create(worker_thread, NULL); + } + worker_thread(NULL); +} + +int master_workers_run(procedure_t worker_fn, void* worker_userdata, + int worker_processes, int worker_threads, bool wait) { +#ifdef OS_WIN + // NOTE: Windows not provide MultiProcesses + if (worker_threads == 0) { + // MultiProcesses => MultiThreads + worker_threads = worker_processes; + } + worker_processes = 0; +#endif + if (worker_threads == 0) worker_threads = 1; + + g_main_ctx.worker_threads = worker_threads; + g_main_ctx.worker_fn = worker_fn; + g_main_ctx.worker_userdata = worker_userdata; + + if (worker_processes == 0) { + // single process + if (wait) { + for (int i = 1; i < worker_threads; ++i) { + hthread_create(worker_thread, NULL); + } + worker_thread(NULL); + } + else { + for (int i = 0; i < worker_threads; ++i) { + hthread_create(worker_thread, NULL); + } + } + } + else { + if (g_main_ctx.worker_processes != 0) { + return ERR_OVER_LIMIT; + } + // master-workers processes +#ifdef OS_UNIX + setproctitle("%s: master process", g_main_ctx.program_name); + signal(SIGNAL_RELOAD, signal_handler); +#endif + g_main_ctx.worker_processes = worker_processes; + int bytes = g_main_ctx.worker_processes * sizeof(proc_ctx_t); + SAFE_ALLOC(g_main_ctx.proc_ctxs, bytes); + proc_ctx_t* ctx = g_main_ctx.proc_ctxs; + for (int i = 0; i < g_main_ctx.worker_processes; ++i, ++ctx) { + ctx->init = worker_init; + ctx->proc = worker_proc; + hproc_spawn(ctx); + hlogi("workers[%d] start/running, pid=%d", i, ctx->pid); + } + g_main_ctx.pid = getpid(); + hlogi("master start/running, pid=%d", g_main_ctx.pid); + if (wait) { + while (1) hv_sleep (1); + } + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/base/hmain.h b/external/libhv/libhv-1.3.2/base/hmain.h new file mode 100644 index 0000000..3fe6598 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hmain.h @@ -0,0 +1,117 @@ +#ifndef HV_MAIN_H_ +#define HV_MAIN_H_ + +#include "hexport.h" +#include "hplatform.h" +#include "hdef.h" +#include "hproc.h" + +#ifdef _MSC_VER +#pragma comment(lib, "winmm.lib") // for timeSetEvent +#endif + +BEGIN_EXTERN_C + +typedef struct main_ctx_s { + char run_dir[MAX_PATH]; + char program_name[MAX_PATH]; + + char confile[MAX_PATH]; // default etc/${program}.conf + char pidfile[MAX_PATH]; // default logs/${program}.pid + char logfile[MAX_PATH]; // default logs/${program}.log + + pid_t pid; // getpid + pid_t oldpid; // getpid_from_pidfile + + // arg + int argc; + int arg_len; + char** os_argv; + char** save_argv; + char* cmdline; + // parsed arg + int arg_kv_size; + char** arg_kv; + int arg_list_size; + char** arg_list; + + // env + int envc; + int env_len; + char** os_envp; + char** save_envp; + + // signals + procedure_t reload_fn; + void* reload_userdata; + // master workers model + int worker_processes; + int worker_threads; + procedure_t worker_fn; + void* worker_userdata; + proc_ctx_t* proc_ctxs; +} main_ctx_t; + +// arg_type +#define NO_ARGUMENT 0 +#define REQUIRED_ARGUMENT 1 +#define OPTIONAL_ARGUMENT 2 +// option define +#define OPTION_PREFIX '-' +#define OPTION_DELIM '=' +#define OPTION_ENABLE "1" +#define OPTION_DISABLE "0" +typedef struct option_s { + char short_opt; + const char* long_opt; + int arg_type; +} option_t; + +HV_EXPORT int main_ctx_init(int argc, char** argv); +HV_EXPORT void main_ctx_free(void); + +// ls -a -l +// ls -al +// watch -n 10 ls +// watch -n10 ls +HV_EXPORT int parse_opt(int argc, char** argv, const char* opt); +// gcc -g -Wall -O3 -std=cpp main.c +HV_EXPORT int parse_opt_long(int argc, char** argv, const option_t* long_options, int size); +HV_EXPORT const char* get_arg(const char* key); +HV_EXPORT const char* get_env(const char* key); + +#if defined(OS_UNIX) && !HAVE_SETPROCTITLE +HV_EXPORT void setproctitle(const char* fmt, ...); +#endif + +// pidfile +HV_EXPORT int create_pidfile(); +HV_EXPORT void delete_pidfile(void); +HV_EXPORT pid_t getpid_from_pidfile(); + +// signal=[start,stop,restart,status,reload] +HV_EXPORT int signal_init(procedure_t reload_fn DEFAULT(NULL), void* reload_userdata DEFAULT(NULL)); +HV_EXPORT void signal_handle(const char* signal); +#ifdef OS_UNIX +// we use SIGTERM to quit process, SIGUSR1 to reload confile +#define SIGNAL_TERMINATE SIGTERM +#define SIGNAL_RELOAD SIGUSR1 +void signal_handler(int signo); +#endif + +// global var +#define DEFAULT_WORKER_PROCESSES 4 +#define MAXNUM_WORKER_PROCESSES 256 +HV_EXPORT extern main_ctx_t g_main_ctx; + +// master-workers processes +HV_EXPORT int master_workers_run( + procedure_t worker_fn, + void* worker_userdata DEFAULT(NULL), + int worker_processes DEFAULT(DEFAULT_WORKER_PROCESSES), + int worker_threads DEFAULT(0), + bool wait DEFAULT(true)); + +END_EXTERN_C + +#endif // HV_MAIN_H_ diff --git a/external/libhv/libhv-1.3.2/base/hmath.h b/external/libhv/libhv-1.3.2/base/hmath.h new file mode 100644 index 0000000..d29fb01 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hmath.h @@ -0,0 +1,68 @@ +#ifndef HV_MATH_H_ +#define HV_MATH_H_ + +#include + +static inline unsigned long floor2e(unsigned long num) { + unsigned long n = num; + int e = 0; + while (n>>=1) ++e; + unsigned long ret = 1; + while (e--) ret<<=1; + return ret; +} + +static inline unsigned long ceil2e(unsigned long num) { + // 2**0 = 1 + if (num == 0 || num == 1) return 1; + unsigned long n = num - 1; + int e = 1; + while (n>>=1) ++e; + unsigned long ret = 1; + while (e--) ret<<=1; + return ret; +} + +// varint little-endian +// MSB +static inline int varint_encode(long long value, unsigned char* buf) { + unsigned char ch; + unsigned char *p = buf; + int bytes = 0; + do { + ch = value & 0x7F; + value >>= 7; + *p++ = value == 0 ? ch : (ch | 0x80); + ++bytes; + } while (value); + return bytes; +} + +// @param[IN|OUT] len: in=>buflen, out=>varint bytesize +static inline long long varint_decode(const unsigned char* buf, int* len) { + long long ret = 0; + int bytes = 0, bits = 0; + const unsigned char *p = buf; + do { + if (len && *len && bytes == *len) { + // Not enough length + *len = 0; + return 0; + } + ret |= ((long long)(*p & 0x7F)) << bits; + ++bytes; + if ((*p & 0x80) == 0) { + // Found end + if (len) *len = bytes; + return ret; + } + ++p; + bits += 7; + } while(bytes < 10); + + // Not found end + if (len) *len = -1; + return ret; +} + +#endif // HV_MATH_H_ diff --git a/external/libhv/libhv-1.3.2/base/hmutex.h b/external/libhv/libhv-1.3.2/base/hmutex.h new file mode 100644 index 0000000..3496039 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hmutex.h @@ -0,0 +1,268 @@ +#ifndef HV_MUTEX_H_ +#define HV_MUTEX_H_ + +#include "hexport.h" +#include "hplatform.h" +#include "htime.h" + +BEGIN_EXTERN_C + +#ifdef OS_WIN +#define hmutex_t CRITICAL_SECTION +#define hmutex_init InitializeCriticalSection +#define hmutex_destroy DeleteCriticalSection +#define hmutex_lock EnterCriticalSection +#define hmutex_unlock LeaveCriticalSection + +#define hrecursive_mutex_t CRITICAL_SECTION +#define hrecursive_mutex_init InitializeCriticalSection +#define hrecursive_mutex_destroy DeleteCriticalSection +#define hrecursive_mutex_lock EnterCriticalSection +#define hrecursive_mutex_unlock LeaveCriticalSection + +#define HSPINLOCK_COUNT -1 +#define hspinlock_t CRITICAL_SECTION +#define hspinlock_init(pspin) InitializeCriticalSectionAndSpinCount(pspin, HSPINLOCK_COUNT) +#define hspinlock_destroy DeleteCriticalSection +#define hspinlock_lock EnterCriticalSection +#define hspinlock_unlock LeaveCriticalSection + +#define hrwlock_t SRWLOCK +#define hrwlock_init InitializeSRWLock +#define hrwlock_destroy(plock) +#define hrwlock_rdlock AcquireSRWLockShared +#define hrwlock_rdunlock ReleaseSRWLockShared +#define hrwlock_wrlock AcquireSRWLockExclusive +#define hrwlock_wrunlock ReleaseSRWLockExclusive + +#define htimed_mutex_t HANDLE +#define htimed_mutex_init(pmutex) *(pmutex) = CreateMutex(NULL, FALSE, NULL) +#define htimed_mutex_destroy(pmutex) CloseHandle(*(pmutex)) +#define htimed_mutex_lock(pmutex) WaitForSingleObject(*(pmutex), INFINITE) +#define htimed_mutex_unlock(pmutex) ReleaseMutex(*(pmutex)) +// true: WAIT_OBJECT_0 +// false: WAIT_OBJECT_TIMEOUT +#define htimed_mutex_lock_for(pmutex, ms) ( WaitForSingleObject(*(pmutex), ms) == WAIT_OBJECT_0 ) + +#define hcondvar_t CONDITION_VARIABLE +#define hcondvar_init InitializeConditionVariable +#define hcondvar_destroy(pcond) +#define hcondvar_wait(pcond, pmutex) SleepConditionVariableCS(pcond, pmutex, INFINITE) +#define hcondvar_wait_for(pcond, pmutex, ms) SleepConditionVariableCS(pcond, pmutex, ms) +#define hcondvar_signal WakeConditionVariable +#define hcondvar_broadcast WakeAllConditionVariable + +#define honce_t INIT_ONCE +#define HONCE_INIT INIT_ONCE_STATIC_INIT +typedef void (*honce_fn)(); +static inline BOOL WINAPI s_once_func(INIT_ONCE* once, PVOID arg, PVOID* _) { + honce_fn fn = (honce_fn)arg; + fn(); + return TRUE; +} +static inline void honce(honce_t* once, honce_fn fn) { + PVOID dummy = NULL; + InitOnceExecuteOnce(once, s_once_func, (PVOID)fn, &dummy); +} + +#define hsem_t HANDLE +#define hsem_init(psem, value) *(psem) = CreateSemaphore(NULL, value, value+100000, NULL) +#define hsem_destroy(psem) CloseHandle(*(psem)) +#define hsem_wait(psem) WaitForSingleObject(*(psem), INFINITE) +#define hsem_post(psem) ReleaseSemaphore(*(psem), 1, NULL) +// true: WAIT_OBJECT_0 +// false: WAIT_OBJECT_TIMEOUT +#define hsem_wait_for(psem, ms) ( WaitForSingleObject(*(psem), ms) == WAIT_OBJECT_0 ) + +#else +#define hmutex_t pthread_mutex_t +#define hmutex_init(pmutex) pthread_mutex_init(pmutex, NULL) +#define hmutex_destroy pthread_mutex_destroy +#define hmutex_lock pthread_mutex_lock +#define hmutex_unlock pthread_mutex_unlock + +#define hrecursive_mutex_t pthread_mutex_t +#define hrecursive_mutex_init(pmutex) \ + do {\ + pthread_mutexattr_t attr;\ + pthread_mutexattr_init(&attr);\ + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);\ + pthread_mutex_init(pmutex, &attr);\ + } while(0) +#define hrecursive_mutex_destroy pthread_mutex_destroy +#define hrecursive_mutex_lock pthread_mutex_lock +#define hrecursive_mutex_unlock pthread_mutex_unlock + +#if HAVE_PTHREAD_SPIN_LOCK +#define hspinlock_t pthread_spinlock_t +#define hspinlock_init(pspin) pthread_spin_init(pspin, PTHREAD_PROCESS_PRIVATE) +#define hspinlock_destroy pthread_spin_destroy +#define hspinlock_lock pthread_spin_lock +#define hspinlock_unlock pthread_spin_unlock +#else +#define hspinlock_t pthread_mutex_t +#define hspinlock_init(pmutex) pthread_mutex_init(pmutex, NULL) +#define hspinlock_destroy pthread_mutex_destroy +#define hspinlock_lock pthread_mutex_lock +#define hspinlock_unlock pthread_mutex_unlock +#endif + +#define hrwlock_t pthread_rwlock_t +#define hrwlock_init(prwlock) pthread_rwlock_init(prwlock, NULL) +#define hrwlock_destroy pthread_rwlock_destroy +#define hrwlock_rdlock pthread_rwlock_rdlock +#define hrwlock_rdunlock pthread_rwlock_unlock +#define hrwlock_wrlock pthread_rwlock_wrlock +#define hrwlock_wrunlock pthread_rwlock_unlock + +#define htimed_mutex_t pthread_mutex_t +#define htimed_mutex_init(pmutex) pthread_mutex_init(pmutex, NULL) +#define htimed_mutex_destroy pthread_mutex_destroy +#define htimed_mutex_lock pthread_mutex_lock +#define htimed_mutex_unlock pthread_mutex_unlock +static inline void timespec_after(struct timespec* ts, unsigned int ms) { + struct timeval tv; + gettimeofday(&tv, NULL); + ts->tv_sec = tv.tv_sec + ms / 1000; + ts->tv_nsec = tv.tv_usec * 1000 + ms % 1000 * 1000000; + if (ts->tv_nsec >= 1000000000) { + ts->tv_nsec -= 1000000000; + ts->tv_sec += 1; + } +} +// true: OK +// false: ETIMEDOUT +static inline int htimed_mutex_lock_for(htimed_mutex_t* mutex, unsigned int ms) { +#if HAVE_PTHREAD_MUTEX_TIMEDLOCK + struct timespec ts; + timespec_after(&ts, ms); + return pthread_mutex_timedlock(mutex, &ts) != ETIMEDOUT; +#else + int ret = 0; + unsigned int end = gettick_ms() + ms; + while ((ret = pthread_mutex_trylock(mutex)) != 0) { + if (gettick_ms() >= end) { + break; + } + hv_msleep(1); + } + return ret == 0; +#endif +} + +#define hcondvar_t pthread_cond_t +#define hcondvar_init(pcond) pthread_cond_init(pcond, NULL) +#define hcondvar_destroy pthread_cond_destroy +#define hcondvar_wait pthread_cond_wait +#define hcondvar_signal pthread_cond_signal +#define hcondvar_broadcast pthread_cond_broadcast +// true: OK +// false: ETIMEDOUT +static inline int hcondvar_wait_for(hcondvar_t* cond, hmutex_t* mutex, unsigned int ms) { + struct timespec ts; + timespec_after(&ts, ms); + return pthread_cond_timedwait(cond, mutex, &ts) != ETIMEDOUT; +} + +#define honce_t pthread_once_t +#define HONCE_INIT PTHREAD_ONCE_INIT +#define honce pthread_once + +#include +#define hsem_t sem_t +#define hsem_init(psem, value) sem_init(psem, 0, value) +#define hsem_destroy sem_destroy +#define hsem_wait sem_wait +#define hsem_post sem_post +// true: OK +// false: ETIMEDOUT +static inline int hsem_wait_for(hsem_t* sem, unsigned int ms) { +#if HAVE_SEM_TIMEDWAIT + struct timespec ts; + timespec_after(&ts, ms); + return sem_timedwait(sem, &ts) != ETIMEDOUT; +#else + int ret = 0; + unsigned int end = gettick_ms() + ms; + while ((ret = sem_trywait(sem)) != 0) { + if (gettick_ms() >= end) { + break; + } + hv_msleep(1); + } + return ret == 0; +#endif +} + +#endif + +END_EXTERN_C + +#ifdef __cplusplus +#include +#include +// using std::mutex; +// NOTE: test std::timed_mutex incorrect in some platforms, use htimed_mutex_t +// using std::timed_mutex; +using std::condition_variable; +using std::lock_guard; +using std::unique_lock; + +BEGIN_NAMESPACE_HV + +class MutexLock { +public: + MutexLock() { hmutex_init(&_mutex); } + ~MutexLock() { hmutex_destroy(&_mutex); } + + void lock() { hmutex_lock(&_mutex); } + void unlock() { hmutex_unlock(&_mutex); } +protected: + hmutex_t _mutex; +}; + +class SpinLock { +public: + SpinLock() { hspinlock_init(&_spin); } + ~SpinLock() { hspinlock_destroy(&_spin); } + + void lock() { hspinlock_lock(&_spin); } + void unlock() { hspinlock_unlock(&_spin); } +protected: + hspinlock_t _spin; +}; + +class RWLock { +public: + RWLock() { hrwlock_init(&_rwlock); } + ~RWLock() { hrwlock_destroy(&_rwlock); } + + void rdlock() { hrwlock_rdlock(&_rwlock); } + void rdunlock() { hrwlock_rdunlock(&_rwlock); } + + void wrlock() { hrwlock_wrlock(&_rwlock); } + void wrunlock() { hrwlock_wrunlock(&_rwlock); } + + void lock() { rdlock(); } + void unlock() { rdunlock(); } +protected: + hrwlock_t _rwlock; +}; + +template +class LockGuard { +public: + LockGuard(T& t) : _lock(t) { _lock.lock(); } + ~LockGuard() { _lock.unlock(); } +protected: + T& _lock; +}; + +END_NAMESPACE_HV + +// same as java synchronized(lock) { ... } +#define synchronized(lock) for (std::lock_guard _lock_(lock), *p = &_lock_; p != NULL; p = NULL) + +#endif // __cplusplus + +#endif // HV_MUTEX_H_ diff --git a/external/libhv/libhv-1.3.2/base/hplatform.h b/external/libhv/libhv-1.3.2/base/hplatform.h new file mode 100644 index 0000000..5e0a290 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hplatform.h @@ -0,0 +1,330 @@ +#ifndef HV_PLATFORM_H_ +#define HV_PLATFORM_H_ + +#include "hconfig.h" + +// OS +#if defined(WIN64) || defined(_WIN64) + #define OS_WIN64 + #define OS_WIN32 +#elif defined(WIN32)|| defined(_WIN32) + #define OS_WIN32 +#elif defined(ANDROID) || defined(__ANDROID__) + #define OS_ANDROID + #define OS_LINUX +#elif defined(linux) || defined(__linux) || defined(__linux__) + #define OS_LINUX +#elif defined(__APPLE__) && (defined(__GNUC__) || defined(__xlC__) || defined(__xlc__)) + #include + #if defined(TARGET_OS_MAC) && TARGET_OS_MAC + #define OS_MAC + #elif defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE + #define OS_IOS + #endif + #define OS_DARWIN +#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) + #define OS_FREEBSD + #define OS_BSD +#elif defined(__NetBSD__) + #define OS_NETBSD + #define OS_BSD +#elif defined(__OpenBSD__) + #define OS_OPENBSD + #define OS_BSD +#elif defined(sun) || defined(__sun) || defined(__sun__) + #define OS_SOLARIS +#else + #warning "Untested operating system platform!" +#endif + +#if defined(OS_WIN32) || defined(OS_WIN64) + #undef OS_UNIX + #define OS_WIN +#else + #define OS_UNIX +#endif + +// ARCH +#if defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) + #define ARCH_X64 + #define ARCH_X86_64 +#elif defined(__i386) || defined(__i386__) || defined(_M_IX86) + #define ARCH_X86 + #define ARCH_X86_32 +#elif defined(__aarch64__) || defined(__ARM64__) || defined(_M_ARM64) + #define ARCH_ARM64 +#elif defined(__arm__) || defined(_M_ARM) + #define ARCH_ARM +#elif defined(__mips64__) + #define ARCH_MIPS64 +#elif defined(__mips__) + #define ARCH_MIPS +#else + #warning "Untested hardware architecture!" +#endif + +// COMPILER +#if defined (_MSC_VER) +#define COMPILER_MSVC + +#if (_MSC_VER < 1200) // Visual C++ 6.0 +#define MSVS_VERSION 1998 +#define MSVC_VERSION 60 +#elif (_MSC_VER >= 1200) && (_MSC_VER < 1300) // Visual Studio 2002, MSVC++ 7.0 +#define MSVS_VERSION 2002 +#define MSVC_VERSION 70 +#elif (_MSC_VER >= 1300) && (_MSC_VER < 1400) // Visual Studio 2003, MSVC++ 7.1 +#define MSVS_VERSION 2003 +#define MSVC_VERSION 71 +#elif (_MSC_VER >= 1400) && (_MSC_VER < 1500) // Visual Studio 2005, MSVC++ 8.0 +#define MSVS_VERSION 2005 +#define MSVC_VERSION 80 +#elif (_MSC_VER >= 1500) && (_MSC_VER < 1600) // Visual Studio 2008, MSVC++ 9.0 +#define MSVS_VERSION 2008 +#define MSVC_VERSION 90 +#elif (_MSC_VER >= 1600) && (_MSC_VER < 1700) // Visual Studio 2010, MSVC++ 10.0 +#define MSVS_VERSION 2010 +#define MSVC_VERSION 100 +#elif (_MSC_VER >= 1700) && (_MSC_VER < 1800) // Visual Studio 2012, MSVC++ 11.0 +#define MSVS_VERSION 2012 +#define MSVC_VERSION 110 +#elif (_MSC_VER >= 1800) && (_MSC_VER < 1900) // Visual Studio 2013, MSVC++ 12.0 +#define MSVS_VERSION 2013 +#define MSVC_VERSION 120 +#elif (_MSC_VER >= 1900) && (_MSC_VER < 1910) // Visual Studio 2015, MSVC++ 14.0 +#define MSVS_VERSION 2015 +#define MSVC_VERSION 140 +#elif (_MSC_VER >= 1910) && (_MSC_VER < 1920) // Visual Studio 2017, MSVC++ 15.0 +#define MSVS_VERSION 2017 +#define MSVC_VERSION 150 +#elif (_MSC_VER >= 1920) && (_MSC_VER < 2000) // Visual Studio 2019, MSVC++ 16.0 +#define MSVS_VERSION 2019 +#define MSVC_VERSION 160 +#endif + +#undef HAVE_STDATOMIC_H +#define HAVE_STDATOMIC_H 0 +#undef HAVE_SYS_TIME_H +#define HAVE_SYS_TIME_H 0 +#undef HAVE_PTHREAD_H +#define HAVE_PTHREAD_H 0 + +#pragma warning (disable: 4018) // signed/unsigned comparison +#pragma warning (disable: 4100) // unused param +#pragma warning (disable: 4102) // unreferenced label +#pragma warning (disable: 4244) // conversion loss of data +#pragma warning (disable: 4267) // size_t => int +#pragma warning (disable: 4819) // Unicode +#pragma warning (disable: 4996) // _CRT_SECURE_NO_WARNINGS + +#elif defined(__GNUC__) +#define COMPILER_GCC + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif + +#elif defined(__clang__) +#define COMPILER_CLANG + +#elif defined(__MINGW32__) || defined(__MINGW64__) +#define COMPILER_MINGW + +#elif defined(__MSYS__) +#define COMPILER_MSYS + +#elif defined(__CYGWIN__) +#define COMPILER_CYGWIN + +#else +#warning "Untested compiler!" +#endif + +// headers +#ifdef OS_WIN + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef _CRT_NONSTDC_NO_DEPRECATE + #define _CRT_NONSTDC_NO_DEPRECATE + #endif + #ifndef _CRT_SECURE_NO_WARNINGS + #define _CRT_SECURE_NO_WARNINGS + #endif + #ifndef _WINSOCK_DEPRECATED_NO_WARNINGS + #define _WINSOCK_DEPRECATED_NO_WARNINGS + #endif + #include + #include // for inet_pton,inet_ntop + #include + #include // for getpid,exec + #include // for mkdir,rmdir,chdir,getcwd + #include // for open,close,read,write,lseek,tell + + #define hv_sleep(s) Sleep((s) * 1000) + #define hv_msleep(ms) Sleep(ms) + #define hv_usleep(us) Sleep((us) / 1000) + #define hv_delay(ms) hv_msleep(ms) + #define hv_mkdir(dir) mkdir(dir) + + // access + #ifndef F_OK + #define F_OK 0 /* test for existence of file */ + #endif + #ifndef X_OK + #define X_OK (1<<0) /* test for execute or search permission */ + #endif + #ifndef W_OK + #define W_OK (1<<1) /* test for write permission */ + #endif + #ifndef R_OK + #define R_OK (1<<2) /* test for read permission */ + #endif + + // stat + #ifndef S_ISREG + #define S_ISREG(st_mode) (((st_mode) & S_IFMT) == S_IFREG) + #endif + #ifndef S_ISDIR + #define S_ISDIR(st_mode) (((st_mode) & S_IFMT) == S_IFDIR) + #endif +#else + #include + #include // for mkdir,rmdir,chdir,getcwd + + // socket + #include + #include + #include + #include + #include + #include + #include // for gethostbyname + + #define hv_sleep(s) sleep(s) + #define hv_msleep(ms) usleep((ms) * 1000) + #define hv_usleep(us) usleep(us) + #define hv_delay(ms) hv_msleep(ms) + #define hv_mkdir(dir) mkdir(dir, 0777) +#endif + +#ifdef _MSC_VER + typedef int pid_t; + typedef int gid_t; + typedef int uid_t; + #define strcasecmp stricmp + #define strncasecmp strnicmp +#else + typedef int BOOL; + typedef unsigned char BYTE; + typedef unsigned short WORD; + typedef void* HANDLE; + #include + #define stricmp strcasecmp + #define strnicmp strncasecmp +#endif + +// ENDIAN +#ifndef BIG_ENDIAN +#define BIG_ENDIAN 4321 +#endif +#ifndef LITTLE_ENDIAN +#define LITTLE_ENDIAN 1234 +#endif +#ifndef NET_ENDIAN +#define NET_ENDIAN BIG_ENDIAN +#endif + +// BYTE_ORDER +#ifndef BYTE_ORDER +#if defined(__BYTE_ORDER) + #define BYTE_ORDER __BYTE_ORDER +#elif defined(__BYTE_ORDER__) + #define BYTE_ORDER __BYTE_ORDER__ +#elif defined(ARCH_X86) || defined(ARCH_X86_64) || \ + defined(__ARMEL__) || defined(__AARCH64EL__) || \ + defined(__MIPSEL) || defined(__MIPS64EL) + #define BYTE_ORDER LITTLE_ENDIAN +#elif defined(__ARMEB__) || defined(__AARCH64EB__) || \ + defined(__MIPSEB) || defined(__MIPS64EB) + #define BYTE_ORDER BIG_ENDIAN +#elif defined(OS_WIN) + #define BYTE_ORDER LITTLE_ENDIAN +#else + #warning "Unknown byte order!" +#endif +#endif + +// ANSI C +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef __cplusplus +#if HAVE_STDBOOL_H +#include +#else + #ifndef bool + #define bool char + #endif + + #ifndef true + #define true 1 + #endif + + #ifndef false + #define false 0 + #endif +#endif +#endif + +#if HAVE_STDINT_H +#include +#elif defined(_MSC_VER) && _MSC_VER < 1700 +typedef __int8 int8_t; +typedef __int16 int16_t; +typedef __int32 int32_t; +typedef __int64 int64_t; +typedef unsigned __int8 uint8_t; +typedef unsigned __int16 uint16_t; +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; +#endif + +typedef float float32_t; +typedef double float64_t; + +typedef int (*method_t)(void* userdata); +typedef void (*procedure_t)(void* userdata); + +#if HAVE_SYS_TYPES_H +#include +#endif + +#if HAVE_SYS_STAT_H +#include +#endif + +#if HAVE_SYS_TIME_H +#include // for gettimeofday +#endif + +#if HAVE_FCNTL_H +#include +#endif + +#if HAVE_PTHREAD_H +#include +#endif + +#endif // HV_PLATFORM_H_ diff --git a/external/libhv/libhv-1.3.2/base/hproc.h b/external/libhv/libhv-1.3.2/base/hproc.h new file mode 100644 index 0000000..b783562 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hproc.h @@ -0,0 +1,69 @@ +#ifndef HV_PROC_H_ +#define HV_PROC_H_ + +#include "hplatform.h" + +typedef struct proc_ctx_s { + pid_t pid; // tid in Windows + time_t start_time; + int spawn_cnt; + procedure_t init; + void* init_userdata; + procedure_t proc; + void* proc_userdata; + procedure_t exit; + void* exit_userdata; +} proc_ctx_t; + +static inline void hproc_run(proc_ctx_t* ctx) { + if (ctx->init) { + ctx->init(ctx->init_userdata); + } + if (ctx->proc) { + ctx->proc(ctx->proc_userdata); + } + if (ctx->exit) { + ctx->exit(ctx->exit_userdata); + } +} + +#ifdef OS_UNIX +// unix use multi-processes +static inline int hproc_spawn(proc_ctx_t* ctx) { + ++ctx->spawn_cnt; + ctx->start_time = time(NULL); + pid_t pid = fork(); + if (pid < 0) { + perror("fork"); + return -1; + } else if (pid == 0) { + // child process + ctx->pid = getpid(); + hproc_run(ctx); + exit(0); + } else if (pid > 0) { + // parent process + ctx->pid = pid; + } + return pid; +} +#elif defined(OS_WIN) +// win32 use multi-threads +static void win_thread(void* userdata) { + proc_ctx_t* ctx = (proc_ctx_t*)userdata; + ctx->pid = GetCurrentThreadId(); // tid in Windows + hproc_run(ctx); +} +static inline int hproc_spawn(proc_ctx_t* ctx) { + ++ctx->spawn_cnt; + ctx->start_time = time(NULL); + HANDLE h = (HANDLE)_beginthread(win_thread, 0, ctx); + if (h == NULL) { + return -1; + } + ctx->pid = GetThreadId(h); // tid in Windows + return ctx->pid; +} +#endif + +#endif // HV_PROC_H_ diff --git a/external/libhv/libhv-1.3.2/base/hsocket.c b/external/libhv/libhv-1.3.2/base/hsocket.c new file mode 100644 index 0000000..12c96eb --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hsocket.c @@ -0,0 +1,408 @@ +#include "hsocket.h" + +#include "hdef.h" + +#ifdef OS_WIN +#include "hatomic.h" +static hatomic_flag_t s_wsa_initialized = HATOMIC_FLAG_INIT; +void WSAInit() { + if (!hatomic_flag_test_and_set(&s_wsa_initialized)) { + WSADATA wsadata; + WSAStartup(MAKEWORD(2, 2), &wsadata); + } +} + +void WSADeinit() { + if (hatomic_flag_test_and_set(&s_wsa_initialized)) { + hatomic_flag_clear(&s_wsa_initialized); + WSACleanup(); + } +} +#endif + +static inline int socket_errno_negative(int sockfd) { + int err = socket_errno(); + if (sockfd >= 0) closesocket(sockfd); + return err > 0 ? -err : -1; +} + +const char* socket_strerror(int err) { +#ifdef OS_WIN + static char buffer[128]; + + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS | + FORMAT_MESSAGE_MAX_WIDTH_MASK, + 0, ABS(err), 0, buffer, sizeof(buffer), NULL); + + return buffer; +#else + return strerror(ABS(err)); +#endif +} + +bool is_ipv4(const char* host) { + struct sockaddr_in sin; + return inet_pton(AF_INET, host, &sin) == 1; +} + +bool is_ipv6(const char* host) { + struct sockaddr_in6 sin6; + return inet_pton(AF_INET6, host, &sin6) == 1; +} + +int ResolveAddr(const char* host, sockaddr_u* addr) { +#ifdef OS_WIN + WSAInit(); +#endif + if (inet_pton(AF_INET, host, &addr->sin.sin_addr) == 1) { + addr->sa.sa_family = AF_INET; // host is ipv4, so easy ;) + return 0; + } + + if (inet_pton(AF_INET6, host, &addr->sin6.sin6_addr) == 1) { + addr->sa.sa_family = AF_INET6; // host is ipv6 + } + + struct addrinfo* ais = NULL; + int ret = getaddrinfo(host, NULL, NULL, &ais); + if (ret != 0 || ais == NULL || ais->ai_addr == NULL || ais->ai_addrlen == 0) { + printd("unknown host: %s err:%d:%s\n", host, ret, gai_strerror(ret)); + return ret; + } + struct addrinfo* pai = ais; + while (pai != NULL) { + if (pai->ai_family == AF_INET) break; + pai = pai->ai_next; + } + if (pai == NULL) pai = ais; + memcpy(addr, pai->ai_addr, pai->ai_addrlen); + freeaddrinfo(ais); + return 0; +} + +const char* sockaddr_ip(sockaddr_u* addr, char *ip, int len) { + if (addr->sa.sa_family == AF_INET) { + return inet_ntop(AF_INET, &addr->sin.sin_addr, ip, len); + } + else if (addr->sa.sa_family == AF_INET6) { + return inet_ntop(AF_INET6, &addr->sin6.sin6_addr, ip, len); + } + return ip; +} + +uint16_t sockaddr_port(sockaddr_u* addr) { + uint16_t port = 0; + if (addr->sa.sa_family == AF_INET) { + port = ntohs(addr->sin.sin_port); + } + else if (addr->sa.sa_family == AF_INET6) { + port = ntohs(addr->sin6.sin6_port); + } + return port; +} + +int sockaddr_set_ip(sockaddr_u* addr, const char* host) { + if (!host || *host == '\0') { + addr->sin.sin_family = AF_INET; + addr->sin.sin_addr.s_addr = htonl(INADDR_ANY); + return 0; + } + return ResolveAddr(host, addr); +} + +void sockaddr_set_port(sockaddr_u* addr, int port) { + if (addr->sa.sa_family == AF_INET) { + addr->sin.sin_port = htons(port); + } + else if (addr->sa.sa_family == AF_INET6) { + addr->sin6.sin6_port = htons(port); + } +} + +int sockaddr_set_ipport(sockaddr_u* addr, const char* host, int port) { +#ifdef ENABLE_UDS + if (port < 0) { + sockaddr_set_path(addr, host); + return 0; + } +#endif + int ret = sockaddr_set_ip(addr, host); + if (ret != 0) return ret; + sockaddr_set_port(addr, port); + // SOCKADDR_PRINT(addr); + return 0; +} + +socklen_t sockaddr_len(sockaddr_u* addr) { + if (addr->sa.sa_family == AF_INET) { + return sizeof(struct sockaddr_in); + } + else if (addr->sa.sa_family == AF_INET6) { + return sizeof(struct sockaddr_in6); + } +#ifdef ENABLE_UDS + else if (addr->sa.sa_family == AF_UNIX) { + return sizeof(struct sockaddr_un); + } +#endif + return sizeof(sockaddr_u); +} + +const char* sockaddr_str(sockaddr_u* addr, char* buf, int len) { + char ip[SOCKADDR_STRLEN] = {0}; + uint16_t port = 0; + if (addr->sa.sa_family == AF_INET) { + inet_ntop(AF_INET, &addr->sin.sin_addr, ip, len); + port = ntohs(addr->sin.sin_port); + snprintf(buf, len, "%s:%d", ip, port); + } + else if (addr->sa.sa_family == AF_INET6) { + inet_ntop(AF_INET6, &addr->sin6.sin6_addr, ip, len); + port = ntohs(addr->sin6.sin6_port); + snprintf(buf, len, "[%s]:%d", ip, port); + } +#ifdef ENABLE_UDS + else if (addr->sa.sa_family == AF_UNIX) { + snprintf(buf, len, "%s", addr->sun.sun_path); + } +#endif + return buf; +} + +static int sockaddr_bind(sockaddr_u* localaddr, int type) { + // socket -> setsockopt -> bind +#ifdef SOCK_CLOEXEC + type |= SOCK_CLOEXEC; +#endif + int sockfd = socket(localaddr->sa.sa_family, type, 0); + if (sockfd < 0) { + perror("socket"); + goto error; + } + +#ifdef OS_UNIX + so_reuseaddr(sockfd, 1); + // so_reuseport(sockfd, 1); +#endif + + if (localaddr->sa.sa_family == AF_INET6) { + ip_v6only(sockfd, 0); + } + + if (bind(sockfd, &localaddr->sa, sockaddr_len(localaddr)) < 0) { + perror("bind"); + goto error; + } + + return sockfd; +error: + return socket_errno_negative(sockfd); +} + +static int sockaddr_connect(sockaddr_u* peeraddr, int nonblock) { + // socket -> nonblocking -> connect + int ret = 0; + int connfd = socket(peeraddr->sa.sa_family, SOCK_STREAM, 0); + if (connfd < 0) { + perror("socket"); + goto error; + } + + if (nonblock) { + nonblocking(connfd); + } + + ret = connect(connfd, &peeraddr->sa, sockaddr_len(peeraddr)); +#ifdef OS_WIN + if (ret < 0 && socket_errno() != WSAEWOULDBLOCK) { +#else + if (ret < 0 && socket_errno() != EINPROGRESS) { +#endif + // perror("connect"); + goto error; + } + + return connfd; +error: + return socket_errno_negative(connfd); +} + +static int ListenFD(int sockfd) { + if (sockfd < 0) return sockfd; + if (listen(sockfd, SOMAXCONN) < 0) { + perror("listen"); + return socket_errno_negative(sockfd); + } + return sockfd; +} + +static int ConnectFDTimeout(int connfd, int ms) { + int err = 0; + socklen_t optlen = sizeof(err); + struct timeval tv = { ms / 1000, (ms % 1000) * 1000 }; + fd_set writefds; + FD_ZERO(&writefds); + FD_SET(connfd, &writefds); + int ret = select(connfd+1, 0, &writefds, 0, &tv); + if (ret < 0) { + perror("select"); + goto error; + } + if (ret == 0) { + errno = ETIMEDOUT; + goto error; + } + if (getsockopt(connfd, SOL_SOCKET, SO_ERROR, (char*)&err, &optlen) < 0 || err != 0) { + if (err != 0) errno = err; + goto error; + } + blocking(connfd); + return connfd; +error: + return socket_errno_negative(connfd); +} + +int Bind(int port, const char* host, int type) { +#ifdef OS_WIN + WSAInit(); +#endif + sockaddr_u localaddr; + memset(&localaddr, 0, sizeof(localaddr)); + int ret = sockaddr_set_ipport(&localaddr, host, port); + if (ret != 0) { + return NABS(ret); + } + return sockaddr_bind(&localaddr, type); +} + +int Listen(int port, const char* host) { + int sockfd = Bind(port, host, SOCK_STREAM); + if (sockfd < 0) return sockfd; + return ListenFD(sockfd); +} + +int Connect(const char* host, int port, int nonblock) { +#ifdef OS_WIN + WSAInit(); +#endif + sockaddr_u peeraddr; + memset(&peeraddr, 0, sizeof(peeraddr)); + int ret = sockaddr_set_ipport(&peeraddr, host, port); + if (ret != 0) { + return NABS(ret); + } + return sockaddr_connect(&peeraddr, nonblock); +} + +int ConnectNonblock(const char* host, int port) { + return Connect(host, port, 1); +} + +int ConnectTimeout(const char* host, int port, int ms) { + int connfd = Connect(host, port, 1); + if (connfd < 0) return connfd; + return ConnectFDTimeout(connfd, ms); +} + +#ifdef ENABLE_UDS +int BindUnix(const char* path, int type) { + sockaddr_u localaddr; + memset(&localaddr, 0, sizeof(localaddr)); + sockaddr_set_path(&localaddr, path); + return sockaddr_bind(&localaddr, type); +} + +int ListenUnix(const char* path) { + int sockfd = BindUnix(path, SOCK_STREAM); + if (sockfd < 0) return sockfd; + return ListenFD(sockfd); +} + +int ConnectUnix(const char* path, int nonblock) { + sockaddr_u peeraddr; + memset(&peeraddr, 0, sizeof(peeraddr)); + sockaddr_set_path(&peeraddr, path); + return sockaddr_connect(&peeraddr, nonblock); +} + +int ConnectUnixNonblock(const char* path) { + return ConnectUnix(path, 1); +} + +int ConnectUnixTimeout(const char* path, int ms) { + int connfd = ConnectUnix(path, 1); + if (connfd < 0) return connfd; + return ConnectFDTimeout(connfd, ms); +} +#endif + +int Socketpair(int family, int type, int protocol, int sv[2]) { +#if defined(OS_UNIX) && HAVE_SOCKETPAIR + return socketpair(AF_LOCAL, type, protocol, sv); +#endif + if (family != AF_INET || type != SOCK_STREAM) { + return -1; + } +#ifdef OS_WIN + WSAInit(); +#endif + int listenfd, connfd, acceptfd; + listenfd = connfd = acceptfd = INVALID_SOCKET; + struct sockaddr_in localaddr; + socklen_t addrlen = sizeof(localaddr); + memset(&localaddr, 0, addrlen); + localaddr.sin_family = AF_INET; + localaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + localaddr.sin_port = 0; + // listener + listenfd = socket(AF_INET, SOCK_STREAM, 0); + if (listenfd < 0) { + perror("socket"); + goto error; + } + if (bind(listenfd, (struct sockaddr*)&localaddr, addrlen) < 0) { + perror("bind"); + goto error; + } + if (listen(listenfd, 1) < 0) { + perror("listen"); + goto error; + } + if (getsockname(listenfd, (struct sockaddr*)&localaddr, &addrlen) < 0) { + perror("getsockname"); + goto error; + } + // connector + connfd = socket(AF_INET, SOCK_STREAM, 0); + if (connfd < 0) { + perror("socket"); + goto error; + } + if (connect(connfd, (struct sockaddr*)&localaddr, addrlen) < 0) { + perror("connect"); + goto error; + } + // acceptor + acceptfd = accept(listenfd, (struct sockaddr*)&localaddr, &addrlen); + if (acceptfd < 0) { + perror("accept"); + goto error; + } + + closesocket(listenfd); + sv[0] = connfd; + sv[1] = acceptfd; + return 0; +error: + if (listenfd != INVALID_SOCKET) { + closesocket(listenfd); + } + if (connfd != INVALID_SOCKET) { + closesocket(connfd); + } + if (acceptfd != INVALID_SOCKET) { + closesocket(acceptfd); + } + return -1; +} diff --git a/external/libhv/libhv-1.3.2/base/hsocket.h b/external/libhv/libhv-1.3.2/base/hsocket.h new file mode 100644 index 0000000..7885230 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hsocket.h @@ -0,0 +1,272 @@ +#ifndef HV_SOCKET_H_ +#define HV_SOCKET_H_ + +#include "hexport.h" +#include "hplatform.h" + +#ifdef ENABLE_UDS +#ifdef OS_WIN + #include // import struct sockaddr_un +#else + #include // import struct sockaddr_un +#endif +#endif + +#ifdef _MSC_VER +#pragma comment(lib, "ws2_32.lib") +#endif + +#define LOCALHOST "127.0.0.1" +#define ANYADDR "0.0.0.0" + +BEGIN_EXTERN_C + +HV_INLINE int socket_errno() { +#ifdef OS_WIN + return WSAGetLastError(); +#else + return errno; +#endif +} +HV_EXPORT const char* socket_strerror(int err); + +#ifdef OS_WIN + +typedef int socklen_t; + +void WSAInit(); +void WSADeinit(); + +HV_INLINE int blocking(int sockfd) { + unsigned long nb = 0; + return ioctlsocket(sockfd, FIONBIO, &nb); +} +HV_INLINE int nonblocking(int sockfd) { + unsigned long nb = 1; + return ioctlsocket(sockfd, FIONBIO, &nb); +} + +#undef EAGAIN +#define EAGAIN WSAEWOULDBLOCK + +#undef EINPROGRESS +#define EINPROGRESS WSAEINPROGRESS + +#undef EINTR +#define EINTR WSAEINTR + +#undef ENOTSOCK +#define ENOTSOCK WSAENOTSOCK + +#undef EMSGSIZE +#define EMSGSIZE WSAEMSGSIZE + +#else + +#define blocking(s) fcntl(s, F_SETFL, fcntl(s, F_GETFL) & ~O_NONBLOCK) +#define nonblocking(s) fcntl(s, F_SETFL, fcntl(s, F_GETFL) | O_NONBLOCK) + +typedef int SOCKET; +#define INVALID_SOCKET -1 + +HV_INLINE int closesocket(int sockfd) { + return close(sockfd); +} + +#endif + +#ifndef SAFE_CLOSESOCKET +#define SAFE_CLOSESOCKET(fd) do {if ((fd) >= 0) {closesocket(fd); (fd) = -1;}} while(0) +#endif + +//-----------------------------sockaddr_u---------------------------------------------- +typedef union { + struct sockaddr sa; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; +#ifdef ENABLE_UDS + struct sockaddr_un sun; +#endif +} sockaddr_u; + +HV_EXPORT bool is_ipv4(const char* host); +HV_EXPORT bool is_ipv6(const char* host); +HV_INLINE bool is_ipaddr(const char* host) { + return is_ipv4(host) || is_ipv6(host); +} + +// @param host: domain or ip +// @retval 0:succeed +HV_EXPORT int ResolveAddr(const char* host, sockaddr_u* addr); + +HV_EXPORT const char* sockaddr_ip(sockaddr_u* addr, char *ip, int len); +HV_EXPORT uint16_t sockaddr_port(sockaddr_u* addr); +HV_EXPORT int sockaddr_set_ip(sockaddr_u* addr, const char* host); +HV_EXPORT void sockaddr_set_port(sockaddr_u* addr, int port); +HV_EXPORT int sockaddr_set_ipport(sockaddr_u* addr, const char* host, int port); +HV_EXPORT socklen_t sockaddr_len(sockaddr_u* addr); +HV_EXPORT const char* sockaddr_str(sockaddr_u* addr, char* buf, int len); + +//#define INET_ADDRSTRLEN 16 +//#define INET6_ADDRSTRLEN 46 +#ifdef ENABLE_UDS +#define SOCKADDR_STRLEN sizeof(((struct sockaddr_un*)(NULL))->sun_path) +HV_INLINE void sockaddr_set_path(sockaddr_u* addr, const char* path) { + addr->sa.sa_family = AF_UNIX; + strncpy(addr->sun.sun_path, path, sizeof(addr->sun.sun_path)); +} +#else +#define SOCKADDR_STRLEN 64 // ipv4:port | [ipv6]:port +#endif + +HV_INLINE void sockaddr_print(sockaddr_u* addr) { + char buf[SOCKADDR_STRLEN] = {0}; + sockaddr_str(addr, buf, sizeof(buf)); + puts(buf); +} + +#define SOCKADDR_LEN(addr) sockaddr_len((sockaddr_u*)addr) +#define SOCKADDR_STR(addr, buf) sockaddr_str((sockaddr_u*)addr, buf, sizeof(buf)) +#define SOCKADDR_PRINT(addr) sockaddr_print((sockaddr_u*)addr) +//===================================================================================== + +// socket -> setsockopt -> bind +// @param type: SOCK_STREAM(tcp) SOCK_DGRAM(udp) +// @return sockfd +HV_EXPORT int Bind(int port, const char* host DEFAULT(ANYADDR), int type DEFAULT(SOCK_STREAM)); + +// Bind -> listen +// @return listenfd +HV_EXPORT int Listen(int port, const char* host DEFAULT(ANYADDR)); + +// @return connfd +// ResolveAddr -> socket -> nonblocking -> connect +HV_EXPORT int Connect(const char* host, int port, int nonblock DEFAULT(0)); +// Connect(host, port, 1) +HV_EXPORT int ConnectNonblock(const char* host, int port); +// Connect(host, port, 1) -> select -> blocking +#define DEFAULT_CONNECT_TIMEOUT 10000 // ms +HV_EXPORT int ConnectTimeout(const char* host, int port, int ms DEFAULT(DEFAULT_CONNECT_TIMEOUT)); + +#ifdef ENABLE_UDS +HV_EXPORT int BindUnix(const char* path, int type DEFAULT(SOCK_STREAM)); +HV_EXPORT int ListenUnix(const char* path); +HV_EXPORT int ConnectUnix(const char* path, int nonblock DEFAULT(0)); +HV_EXPORT int ConnectUnixNonblock(const char* path); +HV_EXPORT int ConnectUnixTimeout(const char* path, int ms DEFAULT(DEFAULT_CONNECT_TIMEOUT)); +#endif + +// Just implement Socketpair(AF_INET, SOCK_STREAM, 0, sv); +HV_EXPORT int Socketpair(int family, int type, int protocol, int sv[2]); + +HV_INLINE int tcp_nodelay(int sockfd, int on DEFAULT(1)) { + return setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(int)); +} + +HV_INLINE int tcp_nopush(int sockfd, int on DEFAULT(1)) { +#ifdef TCP_NOPUSH + return setsockopt(sockfd, IPPROTO_TCP, TCP_NOPUSH, (const char*)&on, sizeof(int)); +#elif defined(TCP_CORK) + return setsockopt(sockfd, IPPROTO_TCP, TCP_CORK, (const char*)&on, sizeof(int)); +#else + return 0; +#endif +} + +HV_INLINE int tcp_keepalive(int sockfd, int on DEFAULT(1), int delay DEFAULT(60)) { + if (setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(int)) != 0) { + return socket_errno(); + } + +#ifdef TCP_KEEPALIVE + return setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE, (const char*)&delay, sizeof(int)); +#elif defined(TCP_KEEPIDLE) + // TCP_KEEPIDLE => tcp_keepalive_time + // TCP_KEEPCNT => tcp_keepalive_probes + // TCP_KEEPINTVL => tcp_keepalive_intvl + return setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (const char*)&delay, sizeof(int)); +#else + return 0; +#endif +} + +HV_INLINE int udp_broadcast(int sockfd, int on DEFAULT(1)) { + return setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (const char*)&on, sizeof(int)); +} + +HV_INLINE int ip_v6only(int sockfd, int on DEFAULT(1)) { +#ifdef IPV6_V6ONLY + return setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&on, sizeof(int)); +#else + return 0; +#endif +} + +// send timeout +HV_INLINE int so_sndtimeo(int sockfd, int timeout) { +#ifdef OS_WIN + return setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&timeout, sizeof(int)); +#else + struct timeval tv = {timeout/1000, (timeout%1000)*1000}; + return setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); +#endif +} + +// recv timeout +HV_INLINE int so_rcvtimeo(int sockfd, int timeout) { +#ifdef OS_WIN + return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(int)); +#else + struct timeval tv = {timeout/1000, (timeout%1000)*1000}; + return setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); +#endif +} + +// send buffer size +HV_INLINE int so_sndbuf(int sockfd, int len) { + return setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, (const char*)&len, sizeof(int)); +} + +// recv buffer size +HV_INLINE int so_rcvbuf(int sockfd, int len) { + return setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (const char*)&len, sizeof(int)); +} + +HV_INLINE int so_reuseaddr(int sockfd, int on DEFAULT(1)) { +#ifdef SO_REUSEADDR + // NOTE: SO_REUSEADDR allow to reuse sockaddr of TIME_WAIT status + return setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(int)); +#else + return 0; +#endif +} + +HV_INLINE int so_reuseport(int sockfd, int on DEFAULT(1)) { +#ifdef SO_REUSEPORT + // NOTE: SO_REUSEPORT allow multiple sockets to bind same port + return setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&on, sizeof(int)); +#else + return 0; +#endif +} + +HV_INLINE int so_linger(int sockfd, int timeout DEFAULT(1)) { +#ifdef SO_LINGER + struct linger linger; + if (timeout >= 0) { + linger.l_onoff = 1; + linger.l_linger = timeout; + } else { + linger.l_onoff = 0; + linger.l_linger = 0; + } + // NOTE: SO_LINGER change the default behavior of close, send RST, avoid TIME_WAIT + return setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger, sizeof(linger)); +#else + return 0; +#endif +} + +END_EXTERN_C + +#endif // HV_SOCKET_H_ diff --git a/external/libhv/libhv-1.3.2/base/hsysinfo.h b/external/libhv/libhv-1.3.2/base/hsysinfo.h new file mode 100644 index 0000000..5366aa5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hsysinfo.h @@ -0,0 +1,68 @@ +#ifndef HV_SYS_INFO_H_ +#define HV_SYS_INFO_H_ + +#include "hplatform.h" + +#ifdef OS_LINUX +#include +#endif + +#ifdef OS_DARWIN +#include +#include +#endif + +static inline int get_ncpu() { +#ifdef OS_WIN + SYSTEM_INFO si; + GetSystemInfo(&si); + return si.dwNumberOfProcessors; +#else + //return get_nprocs(); + //return get_nprocs_conf(); + //return sysconf(_SC_NPROCESSORS_ONLN); // processors available + return sysconf(_SC_NPROCESSORS_CONF); // processors configured +#endif +} + +typedef struct meminfo_s { + unsigned long total; // KB + unsigned long free; // KB +} meminfo_t; + +static inline int get_meminfo(meminfo_t* mem) { +#ifdef OS_WIN + MEMORYSTATUSEX memstat; + memset(&memstat, 0, sizeof(memstat)); + memstat.dwLength = sizeof(memstat); + GlobalMemoryStatusEx(&memstat); + mem->total = (unsigned long)(memstat.ullTotalPhys >> 10); + mem->free = (unsigned long)(memstat.ullAvailPhys >> 10); + return 0; +#elif defined(OS_LINUX) + struct sysinfo info; + if (sysinfo(&info) < 0) { + return errno; + } + mem->total = info.totalram * info.mem_unit >> 10; + mem->free = info.freeram * info.mem_unit >> 10; + return 0; +#elif defined(OS_DARWIN) + uint64_t memsize = 0; + size_t size = sizeof(memsize); + int which[2] = {CTL_HW, HW_MEMSIZE}; + sysctl(which, 2, &memsize, &size, NULL, 0); + mem->total = memsize >> 10; + + vm_statistics_data_t info; + mach_msg_type_number_t count = sizeof(info) / sizeof(integer_t); + host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&info, &count); + mem->free = ((uint64_t)info.free_count * sysconf(_SC_PAGESIZE)) >> 10; + return 0; +#else + (void)(mem); + return -10; +#endif +} + +#endif // HV_SYS_INFO_H_ diff --git a/external/libhv/libhv-1.3.2/base/hthread.h b/external/libhv/libhv-1.3.2/base/hthread.h new file mode 100644 index 0000000..b43e0c6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hthread.h @@ -0,0 +1,217 @@ +#ifndef HV_THREAD_H_ +#define HV_THREAD_H_ + +#include "hplatform.h" + +#ifdef OS_WIN +#define hv_getpid (long)GetCurrentProcessId +#else +#define hv_getpid (long)getpid +#endif + +#ifdef OS_WIN +#define hv_gettid (long)GetCurrentThreadId +#elif HAVE_GETTID || defined(OS_ANDROID) +#define hv_gettid (long)gettid +#elif defined(OS_LINUX) +#include +#define hv_gettid() (long)syscall(SYS_gettid) +#elif defined(OS_DARWIN) +static inline long hv_gettid() { + uint64_t tid = 0; + pthread_threadid_np(NULL, &tid); + return tid; +} +#elif HAVE_PTHREAD_H +#define hv_gettid (long)pthread_self +#else +#define hv_gettid hv_getpid +#endif + +/* +#include "hthread.h" + +HTHREAD_ROUTINE(thread_demo) { + printf("thread[%ld] start\n", hv_gettid()); + hv_delay(3000); + printf("thread[%ld] end\n", hv_gettid()); + return 0; +} + +int main() { + hthread_t th = hthread_create(thread_demo, NULL); + hthread_join(th); + return 0; +} + */ + +#ifdef OS_WIN +typedef HANDLE hthread_t; +typedef DWORD (WINAPI *hthread_routine)(void*); +#define HTHREAD_RETTYPE DWORD +#define HTHREAD_ROUTINE(fname) DWORD WINAPI fname(void* userdata) +static inline hthread_t hthread_create(hthread_routine fn, void* userdata) { + return CreateThread(NULL, 0, fn, userdata, 0, NULL); +} + +static inline int hthread_join(hthread_t th) { + WaitForSingleObject(th, INFINITE); + CloseHandle(th); + return 0; +} + +#else + +typedef pthread_t hthread_t; +typedef void* (*hthread_routine)(void*); +#define HTHREAD_RETTYPE void* +#define HTHREAD_ROUTINE(fname) void* fname(void* userdata) +static inline hthread_t hthread_create(hthread_routine fn, void* userdata) { + pthread_t th; + pthread_create(&th, NULL, fn, userdata); + return th; +} + +static inline int hthread_join(hthread_t th) { + return pthread_join(th, NULL); +} + +#endif + +#ifdef __cplusplus +/************************************************ + * HThread + * Status: STOP,RUNNING,PAUSE + * Control: start,stop,pause,resume + * first-level virtual: doTask + * second-level virtual: run +************************************************/ +#include +#include +#include + +class HThread { +public: + enum Status { + STOP, + RUNNING, + PAUSE, + }; + + enum SleepPolicy { + YIELD, + SLEEP_FOR, + SLEEP_UNTIL, + NO_SLEEP, + }; + + HThread() { + status = STOP; + status_changed = false; + dotask_cnt = 0; + sleep_policy = YIELD; + sleep_ms = 0; + } + + virtual ~HThread() {} + + void setStatus(Status stat) { + status_changed = true; + status = stat; + } + + void setSleepPolicy(SleepPolicy policy, uint32_t ms = 0) { + sleep_policy = policy; + sleep_ms = ms; + setStatus(status); + } + + virtual int start() { + if (status == STOP) { + thread = std::thread([this] { + if (!doPrepare()) return; + setStatus(RUNNING); + run(); + setStatus(STOP); + if (!doFinish()) return; + }); + } + return 0; + } + + virtual int stop() { + if (status != STOP) { + setStatus(STOP); + } + if (thread.joinable()) { + thread.join(); // wait thread exit + } + return 0; + } + + virtual int pause() { + if (status == RUNNING) { + setStatus(PAUSE); + } + return 0; + } + + virtual int resume() { + if (status == PAUSE) { + setStatus(RUNNING); + } + return 0; + } + + virtual void run() { + while (status != STOP) { + while (status == PAUSE) { + std::this_thread::yield(); + } + + doTask(); + ++dotask_cnt; + + HThread::sleep(); + } + } + + virtual bool doPrepare() {return true;} + virtual void doTask() {} + virtual bool doFinish() {return true;} + + std::thread thread; + std::atomic status; + uint32_t dotask_cnt; +protected: + void sleep() { + switch (sleep_policy) { + case YIELD: + std::this_thread::yield(); + break; + case SLEEP_FOR: + std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms)); + break; + case SLEEP_UNTIL: { + if (status_changed) { + status_changed = false; + base_tp = std::chrono::steady_clock::now(); + } + base_tp += std::chrono::milliseconds(sleep_ms); + std::this_thread::sleep_until(base_tp); + } + break; + default: // donothing, go all out. + break; + } + } + + SleepPolicy sleep_policy; + uint32_t sleep_ms; + // for SLEEP_UNTIL + std::atomic status_changed; + std::chrono::steady_clock::time_point base_tp; +}; +#endif + +#endif // HV_THREAD_H_ diff --git a/external/libhv/libhv-1.3.2/base/htime.c b/external/libhv/libhv-1.3.2/base/htime.c new file mode 100644 index 0000000..6f1542e --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/htime.c @@ -0,0 +1,290 @@ +#include "htime.h" + +static const char* s_weekdays[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; + +static const char* s_months[] = {"January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"}; + +static const uint8_t s_days[] = \ +// 1 3 5 7 8 10 12 + {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + +unsigned int gettick_ms() { +#ifdef OS_WIN + return GetTickCount(); +#elif HAVE_CLOCK_GETTIME + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +#else + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000 + tv.tv_usec / 1000; +#endif +} + +unsigned long long gethrtime_us() { +#ifdef OS_WIN + static LONGLONG s_freq = 0; + if (s_freq == 0) { + LARGE_INTEGER freq; + QueryPerformanceFrequency(&freq); + s_freq = freq.QuadPart; + } + if (s_freq != 0) { + LARGE_INTEGER count; + QueryPerformanceCounter(&count); + return (unsigned long long)(count.QuadPart / (double)s_freq * 1000000); + } + return 0; +#elif defined(OS_SOLARIS) + return gethrtime() / 1000; +#elif HAVE_CLOCK_GETTIME + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return ts.tv_sec*(unsigned long long)1000000 + ts.tv_nsec / 1000; +#else + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec*(unsigned long long)1000000 + tv.tv_usec; +#endif +} + +datetime_t datetime_now() { +#ifdef OS_WIN + SYSTEMTIME tm; + GetLocalTime(&tm); + datetime_t dt; + dt.year = tm.wYear; + dt.month = tm.wMonth; + dt.day = tm.wDay; + dt.hour = tm.wHour; + dt.min = tm.wMinute; + dt.sec = tm.wSecond; + dt.ms = tm.wMilliseconds; + return dt; +#else + struct timeval tv; + gettimeofday(&tv, NULL); + datetime_t dt = datetime_localtime(tv.tv_sec); + dt.ms = tv.tv_usec / 1000; + return dt; +#endif +} + +datetime_t datetime_localtime(time_t seconds) { + struct tm* tm = localtime(&seconds); + datetime_t dt; + dt.year = tm->tm_year + 1900; + dt.month = tm->tm_mon + 1; + dt.day = tm->tm_mday; + dt.hour = tm->tm_hour; + dt.min = tm->tm_min; + dt.sec = tm->tm_sec; + return dt; +} + +time_t datetime_mktime(datetime_t* dt) { + struct tm tm; + time_t ts; + time(&ts); + struct tm* ptm = localtime(&ts); + memcpy(&tm, ptm, sizeof(struct tm)); + tm.tm_year = dt->year - 1900; + tm.tm_mon = dt->month - 1; + tm.tm_mday = dt->day; + tm.tm_hour = dt->hour; + tm.tm_min = dt->min; + tm.tm_sec = dt->sec; + return mktime(&tm); +} + +int days_of_month(int month, int year) { + if (month < 1 || month > 12) { + return 0; + } + int days = s_days[month-1]; + return (month == 2 && IS_LEAP_YEAR(year)) ? ++days : days; +} + +datetime_t* datetime_past(datetime_t* dt, int days) { + assert(days >= 0); + int sub = days; + while (sub) { + if (dt->day > sub) { + dt->day -= sub; + break; + } + sub -= dt->day; + if (--dt->month == 0) { + dt->month = 12; + --dt->year; + } + dt->day = days_of_month(dt->month, dt->year); + } + return dt; +} + +datetime_t* datetime_future(datetime_t* dt, int days) { + assert(days >= 0); + int sub = days; + int mdays; + while (sub) { + mdays = days_of_month(dt->month, dt->year); + if (dt->day + sub <= mdays) { + dt->day += sub; + break; + } + sub -= (mdays - dt->day + 1); + if (++dt->month > 12) { + dt->month = 1; + ++dt->year; + } + dt->day = 1; + } + return dt; +} + +char* duration_fmt(int sec, char* buf) { + int h, m, s; + m = sec / 60; + s = sec % 60; + h = m / 60; + m = m % 60; + sprintf(buf, TIME_FMT, h, m, s); + return buf; +} + +char* datetime_fmt(datetime_t* dt, char* buf) { + sprintf(buf, DATETIME_FMT, + dt->year, dt->month, dt->day, + dt->hour, dt->min, dt->sec); + return buf; +} + +char* datetime_fmt_iso(datetime_t* dt, char* buf) { + sprintf(buf, DATETIME_FMT_ISO, + dt->year, dt->month, dt->day, + dt->hour, dt->min, dt->sec, + dt->ms); + return buf; +} + +char* gmtime_fmt(time_t time, char* buf) { + struct tm* tm = gmtime(&time); + //strftime(buf, GMTIME_FMT_BUFLEN, "%a, %d %b %Y %H:%M:%S GMT", tm); + sprintf(buf, GMTIME_FMT, + s_weekdays[tm->tm_wday], + tm->tm_mday, s_months[tm->tm_mon], tm->tm_year + 1900, + tm->tm_hour, tm->tm_min, tm->tm_sec); + return buf; +} + +int month_atoi(const char* month) { + for (size_t i = 0; i < 12; ++i) { + if (strnicmp(month, s_months[i], strlen(month)) == 0) + return i+1; + } + return 0; +} + +const char* month_itoa(int month) { + assert(month >= 1 && month <= 12); + return s_months[month-1]; +} + +int weekday_atoi(const char* weekday) { + for (size_t i = 0; i < 7; ++i) { + if (strnicmp(weekday, s_weekdays[i], strlen(weekday)) == 0) + return i; + } + return 0; +} + +const char* weekday_itoa(int weekday) { + assert(weekday >= 0 && weekday <= 7); + if (weekday == 7) weekday = 0; + return s_weekdays[weekday]; +} + +datetime_t hv_compile_datetime() { + datetime_t dt; + char month[32]; + sscanf(__DATE__, "%s %d %d", month, &dt.day, &dt.year); + sscanf(__TIME__, "%d:%d:%d", &dt.hour, &dt.min, &dt.sec); + dt.month = month_atoi(month); + return dt; +} + +time_t cron_next_timeout(int minute, int hour, int day, int week, int month) { + enum { + MINUTELY, + HOURLY, + DAILY, + WEEKLY, + MONTHLY, + YEARLY, + } period_type = MINUTELY; + struct tm tm; + time_t tt; + time(&tt); + tm = *localtime(&tt); + time_t tt_round = 0; + + tm.tm_sec = 0; + if (minute >= 0) { + period_type = HOURLY; + tm.tm_min = minute; + } + if (hour >= 0) { + period_type = DAILY; + tm.tm_hour = hour; + } + if (week >= 0) { + period_type = WEEKLY; + } + else if (day > 0) { + period_type = MONTHLY; + tm.tm_mday = day; + if (month > 0) { + period_type = YEARLY; + tm.tm_mon = month - 1; + } + } + + tt_round = mktime(&tm); + if (week >= 0) { + tt_round += (week-tm.tm_wday)*SECONDS_PER_DAY; + } + if (tt_round > tt) { + return tt_round; + } + + switch(period_type) { + case MINUTELY: + tt_round += SECONDS_PER_MINUTE; + return tt_round; + case HOURLY: + tt_round += SECONDS_PER_HOUR; + return tt_round; + case DAILY: + tt_round += SECONDS_PER_DAY; + return tt_round; + case WEEKLY: + tt_round += SECONDS_PER_WEEK; + return tt_round; + case MONTHLY: + if (++tm.tm_mon == 12) { + tm.tm_mon = 0; + ++tm.tm_year; + } + break; + case YEARLY: + ++tm.tm_year; + break; + default: + return -1; + } + + return mktime(&tm); +} diff --git a/external/libhv/libhv-1.3.2/base/htime.h b/external/libhv/libhv-1.3.2/base/htime.h new file mode 100644 index 0000000..4d6dd01 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/htime.h @@ -0,0 +1,114 @@ +#ifndef HV_TIME_H_ +#define HV_TIME_H_ + +#include "hexport.h" +#include "hplatform.h" + +BEGIN_EXTERN_C + +#define SECONDS_PER_MINUTE 60 +#define SECONDS_PER_HOUR 3600 +#define SECONDS_PER_DAY 86400 // 24*3600 +#define SECONDS_PER_WEEK 604800 // 7*24*3600 + +#define IS_LEAP_YEAR(year) (((year)%4 == 0 && (year)%100 != 0) || (year)%400 == 0) + +typedef struct datetime_s { + int year; + int month; + int day; + int hour; + int min; + int sec; + int ms; +} datetime_t; + +#ifdef _MSC_VER +/* @see winsock2.h +// Structure used in select() call, taken from the BSD file sys/time.h +struct timeval { + long tv_sec; + long tv_usec; +}; +*/ + +struct timezone { + int tz_minuteswest; /* of Greenwich */ + int tz_dsttime; /* type of dst correction to apply */ +}; + +#include +HV_INLINE int gettimeofday(struct timeval *tv, struct timezone *tz) { + struct _timeb tb; + _ftime(&tb); + if (tv) { + tv->tv_sec = (long)tb.time; + tv->tv_usec = tb.millitm * 1000; + } + if (tz) { + tz->tz_minuteswest = tb.timezone; + tz->tz_dsttime = tb.dstflag; + } + return 0; +} +#endif + +HV_EXPORT unsigned int gettick_ms(); +HV_INLINE unsigned long long gettimeofday_ms() { + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * (unsigned long long)1000 + tv.tv_usec/1000; +} +HV_INLINE unsigned long long gettimeofday_us() { + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * (unsigned long long)1000000 + tv.tv_usec; +} +HV_EXPORT unsigned long long gethrtime_us(); + +HV_EXPORT datetime_t datetime_now(); +HV_EXPORT datetime_t datetime_localtime(time_t seconds); +HV_EXPORT time_t datetime_mktime(datetime_t* dt); + +HV_EXPORT datetime_t* datetime_past(datetime_t* dt, int days DEFAULT(1)); +HV_EXPORT datetime_t* datetime_future(datetime_t* dt, int days DEFAULT(1)); + +#define TIME_FMT "%02d:%02d:%02d" +#define TIME_FMT_BUFLEN 12 +HV_EXPORT char* duration_fmt(int sec, char* buf); + +#define DATETIME_FMT "%04d-%02d-%02d %02d:%02d:%02d" +#define DATETIME_FMT_ISO "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ" +#define DATETIME_FMT_BUFLEN 30 +HV_EXPORT char* datetime_fmt(datetime_t* dt, char* buf); +HV_EXPORT char* datetime_fmt_iso(datetime_t* dt, char* buf); + +#define GMTIME_FMT "%.3s, %02d %.3s %04d %02d:%02d:%02d GMT" +#define GMTIME_FMT_BUFLEN 30 +HV_EXPORT char* gmtime_fmt(time_t time, char* buf); + +HV_EXPORT int days_of_month(int month, int year); + +HV_EXPORT int month_atoi(const char* month); +HV_EXPORT const char* month_itoa(int month); + +HV_EXPORT int weekday_atoi(const char* weekday); +HV_EXPORT const char* weekday_itoa(int weekday); + +HV_EXPORT datetime_t hv_compile_datetime(); + +/* + * minute hour day week month action + * 0~59 0~23 1~31 0~6 1~12 + * -1 -1 -1 -1 -1 cron.minutely + * 30 -1 -1 -1 -1 cron.hourly + * 30 1 -1 -1 -1 cron.daily + * 30 1 15 -1 -1 cron.monthly + * 30 1 -1 0 -1 cron.weekly + * 30 1 1 -1 10 cron.yearly + */ +HV_EXPORT time_t cron_next_timeout(int minute, int hour, int day, int week, int month); + +END_EXTERN_C + +#endif // HV_TIME_H_ diff --git a/external/libhv/libhv-1.3.2/base/hversion.c b/external/libhv/libhv-1.3.2/base/hversion.c new file mode 100644 index 0000000..31a97d9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hversion.c @@ -0,0 +1,48 @@ +#include "hversion.h" + +#include "htime.h" + +const char* hv_compile_version() { + static char s_version[16] = {0}; + datetime_t dt = hv_compile_datetime(); + snprintf(s_version, sizeof(s_version), "%d.%d.%d.%d", + HV_VERSION_MAJOR, dt.year%100, dt.month, dt.day); + return s_version; +} + +int version_atoi(const char* str) { + int hex = 0; + + // trim v1.2.3.4 + const char* pv = strchr(str, 'v'); + const char* pdot = pv ? pv+1 : str; + + while (1) { + hex = (hex << 8) | atoi(pdot); + pdot = strchr(pdot, '.'); + if (pdot == NULL) break; + ++pdot; + } + + return hex; +} + +void version_itoa(int num, char* str) { + char* ch = (char*)# + sprintf(str, "%d.%d.%d.%d", ch[3], ch[2], ch[1], ch[0]); + + // trim 0.1.2.3 + const char* p = str; + while (1) { + if (p[0] == '0' && p[1] == '.') { + p += 2; + } + else { + break; + } + } + + if (p != str) { + strcpy(str, p); + } +} diff --git a/external/libhv/libhv-1.3.2/base/hversion.h b/external/libhv/libhv-1.3.2/base/hversion.h new file mode 100644 index 0000000..d88dd42 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/hversion.h @@ -0,0 +1,34 @@ +#ifndef HV_VERSION_H_ +#define HV_VERSION_H_ + +#include "hexport.h" +#include "hdef.h" + +BEGIN_EXTERN_C + +#define HV_VERSION_MAJOR 1 +#define HV_VERSION_MINOR 3 +#define HV_VERSION_PATCH 2 + +#define HV_VERSION_STRING STRINGIFY(HV_VERSION_MAJOR) "." \ + STRINGIFY(HV_VERSION_MINOR) "." \ + STRINGIFY(HV_VERSION_PATCH) + +#define HV_VERSION_NUMBER ((HV_VERSION_MAJOR << 16) | (HV_VERSION_MINOR << 8) | HV_VERSION_PATCH) + + +HV_INLINE const char* hv_version() { + return HV_VERSION_STRING; +} + +HV_EXPORT const char* hv_compile_version(); + +// 1.2.3.4 => 0x01020304 +HV_EXPORT int version_atoi(const char* str); + +// 0x01020304 => 1.2.3.4 +HV_EXPORT void version_itoa(int hex, char* str); + +END_EXTERN_C + +#endif // HV_VERSION_H_ diff --git a/external/libhv/libhv-1.3.2/base/list.h b/external/libhv/libhv-1.3.2/base/list.h new file mode 100644 index 0000000..97a7d7a --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/list.h @@ -0,0 +1,733 @@ +#ifndef _LINUX_LIST_H +#define _LINUX_LIST_H + +/* + * Simple doubly linked list implementation. + * + * Some of the internal functions ("__xxx") are useful when + * manipulating whole lists rather than single entries, as + * sometimes we already know the next/prev entries and we can + * generate better code by using them directly rather than + * using the generic single-entry routines. + */ + +#include + +#ifndef prefetch +#ifdef __GNUC__ + #define prefetch(x) __builtin_prefetch(x) +#else + #define prefetch(x) (void)0 +#endif +#endif + +struct list_head { + struct list_head *next, *prev; +}; +#define list_node list_head + +struct hlist_head { + struct hlist_node *first; +}; + +struct hlist_node { + struct hlist_node *next, **pprev; +}; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } +// TODO: defined LIST_HEAD +#ifndef LIST_HEAD +#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) +#endif +#define INIT_LIST_HEAD list_init +static inline void list_init(struct list_head *list) +{ + list->next = list; + list->prev = list; +} + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add(struct list_head *n, + struct list_head *prev, + struct list_head *next) +{ + next->prev = n; + n->next = next; + n->prev = prev; + prev->next = n; +} + +/** + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *n, struct list_head *head) +{ + __list_add(n, head, head->next); +} + + +/** + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *n, struct list_head *head) +{ + __list_add(n, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head * prev, struct list_head * next) +{ + next->prev = prev; + prev->next = next; +} + +/** + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty() on entry does not return true after this, the entry is + * in an undefined state. + */ +static inline void __list_del_entry(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); +} + +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + //entry->next = NULL; + //entry->prev = NULL; +} + +/** + * list_replace - replace old entry by new one + * @old : the element to be replaced + * @new : the new element to insert + * + * If @old was empty, it will be overwritten. + */ +static inline void list_replace(struct list_head *old, + struct list_head *n) +{ + n->next = old->next; + n->next->prev = n; + n->prev = old->prev; + n->prev->next = n; +} + +static inline void list_replace_init(struct list_head *old, + struct list_head *n) +{ + list_replace(old, n); + INIT_LIST_HEAD(old); +} + +/** + * list_del_init - deletes entry from list and reinitialize it. + * @entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del_entry(entry); + INIT_LIST_HEAD(entry); +} + +/** + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del_entry(list); + list_add(list, head); +} + +/** + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del_entry(list); + list_add_tail(list, head); +} + +/** + * list_is_last - tests whether @list is the last entry in list @head + * @list: the entry to test + * @head: the head of the list + */ +static inline int list_is_last(const struct list_head *list, + const struct list_head *head) +{ + return list->next == head; +} + +/** + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +/** + * list_empty_careful - tests whether a list is empty and not being modified + * @head: the list to test + * + * Description: + * tests whether a list is empty _and_ checks that no other CPU might be + * in the process of modifying either member (next or prev) + * + * NOTE: using list_empty_careful() without synchronization + * can only be safe if the only activity that can happen + * to the list entry is list_del_init(). Eg. it cannot be used + * if another CPU could re-list_add() it. + */ +static inline int list_empty_careful(const struct list_head *head) +{ + struct list_head *next = head->next; + return (next == head) && (next == head->prev); +} + +/** + * list_rotate_left - rotate the list to the left + * @head: the head of the list + */ +static inline void list_rotate_left(struct list_head *head) +{ + struct list_head *first; + + if (!list_empty(head)) { + first = head->next; + list_move_tail(first, head); + } +} + +/** + * list_is_singular - tests whether a list has just one entry. + * @head: the list to test. + */ +static inline int list_is_singular(const struct list_head *head) +{ + return !list_empty(head) && (head->next == head->prev); +} + +static inline void __list_cut_position(struct list_head *list, + struct list_head *head, struct list_head *entry) +{ + struct list_head *new_first = entry->next; + list->next = head->next; + list->next->prev = list; + list->prev = entry; + entry->next = list; + head->next = new_first; + new_first->prev = head; +} + +/** + * list_cut_position - cut a list into two + * @list: a new list to add all removed entries + * @head: a list with entries + * @entry: an entry within head, could be the head itself + * and if so we won't cut the list + * + * This helper moves the initial part of @head, up to and + * including @entry, from @head to @list. You should + * pass on @entry an element you know is on @head. @list + * should be an empty list or a list you do not care about + * losing its data. + * + */ +static inline void list_cut_position(struct list_head *list, + struct list_head *head, struct list_head *entry) +{ + if (list_empty(head)) + return; + if (list_is_singular(head) && + (head->next != entry && head != entry)) + return; + if (entry == head) + INIT_LIST_HEAD(list); + else + __list_cut_position(list, head, entry); +} + +static inline void __list_splice(const struct list_head *list, + struct list_head *prev, + struct list_head *next) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + + first->prev = prev; + prev->next = first; + + last->next = next; + next->prev = last; +} + +/** + * list_splice - join two lists, this is designed for stacks + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(const struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head, head->next); +} + +/** + * list_splice_tail - join two lists, each list being a queue + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice_tail(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head->prev, head); +} + +/** + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head, head->next); + INIT_LIST_HEAD(list); + } +} + +/** + * list_splice_tail_init - join two lists and reinitialise the emptied list + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * Each of the lists is a queue. + * The list at @list is reinitialised + */ +static inline void list_splice_tail_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head->prev, head); + INIT_LIST_HEAD(list); + } +} + +/** + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/** + * list_first_entry - get the first element from a list + * @ptr: the list head to take the element from. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + * + * Note, that list is expected to be not empty. + */ +#define list_first_entry(ptr, type, member) \ + list_entry((ptr)->next, type, member) + +/** + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop cursor. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next; prefetch(pos->next), pos != (head); \ + pos = pos->next) + +/** + * __list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop cursor. + * @head: the head for your list. + * + * This variant differs from list_for_each() in that it's the + * simplest possible list iteration code, no prefetching is done. + * Use this for code that knows the list to be very short (empty + * or 1 entry) most of the time. + */ +#define __list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/** + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop cursor. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev; prefetch(pos->prev), pos != (head); \ + pos = pos->prev) + +/** + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop cursor. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * list_for_each_prev_safe - iterate over a list backwards safe against removal of list entry + * @pos: the &struct list_head to use as a loop cursor. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_prev_safe(pos, n, head) \ + for (pos = (head)->prev, n = pos->prev; \ + prefetch(pos->prev), pos != (head); \ + pos = n, n = pos->prev) + +/** + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member); \ + prefetch(pos->member.next), &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/** + * list_for_each_entry_reverse - iterate backwards over list of given type. + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_reverse(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member); \ + prefetch(pos->member.prev), &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) + +/** + * list_prepare_entry - prepare a pos entry for use in list_for_each_entry_continue() + * @pos: the type * to use as a start point + * @head: the head of the list + * @member: the name of the list_struct within the struct. + * + * Prepares a pos entry for use as a start point in list_for_each_entry_continue(). + */ +#define list_prepare_entry(pos, head, member) \ + ((pos) ? : list_entry(head, typeof(*pos), member)) + +/** + * list_for_each_entry_continue - continue iteration over list of given type + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Continue to iterate over list of given type, continuing after + * the current position. + */ +#define list_for_each_entry_continue(pos, head, member) \ + for (pos = list_entry(pos->member.next, typeof(*pos), member); \ + prefetch(pos->member.next), &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/** + * list_for_each_entry_continue_reverse - iterate backwards from the given point + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Start to iterate over list of given type backwards, continuing after + * the current position. + */ +#define list_for_each_entry_continue_reverse(pos, head, member) \ + for (pos = list_entry(pos->member.prev, typeof(*pos), member); \ + prefetch(pos->member.prev), &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member)) + +/** + * list_for_each_entry_from - iterate over list of given type from the current point + * @pos: the type * to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Iterate over list of given type, continuing from current position. + */ +#define list_for_each_entry_from(pos, head, member) \ + for (; prefetch(pos->member.next), &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member)) + +/** + * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @pos: the type * to use as a loop cursor. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + +/** + * list_for_each_entry_safe_continue - continue list iteration safe against removal + * @pos: the type * to use as a loop cursor. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Iterate over list of given type, continuing after current point, + * safe against removal of list entry. + */ +#define list_for_each_entry_safe_continue(pos, n, head, member) \ + for (pos = list_entry(pos->member.next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + +/** + * list_for_each_entry_safe_from - iterate over list from current point safe against removal + * @pos: the type * to use as a loop cursor. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Iterate over list of given type from current point, safe against + * removal of list entry. + */ +#define list_for_each_entry_safe_from(pos, n, head, member) \ + for (n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + +/** + * list_for_each_entry_safe_reverse - iterate backwards over list safe against removal + * @pos: the type * to use as a loop cursor. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * Iterate backwards over list of given type, safe against removal + * of list entry. + */ +#define list_for_each_entry_safe_reverse(pos, n, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member), \ + n = list_entry(pos->member.prev, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.prev, typeof(*n), member)) + +/** + * list_safe_reset_next - reset a stale list_for_each_entry_safe loop + * @pos: the loop cursor used in the list_for_each_entry_safe loop + * @n: temporary storage used in list_for_each_entry_safe + * @member: the name of the list_struct within the struct. + * + * list_safe_reset_next is not safe to use in general if the list may be + * modified concurrently (eg. the lock is dropped in the loop body). An + * exception to this is if the cursor element (pos) is pinned in the list, + * and list_safe_reset_next is called after re-taking the lock and before + * completing the current iteration of the loop body. + */ +#define list_safe_reset_next(pos, n, member) \ + n = list_entry(pos->member.next, typeof(*pos), member) + +/* + * Double linked lists with a single pointer list head. + * Mostly useful for hash tables where the two pointer list head is + * too wasteful. + * You lose the ability to access the tail in O(1). + */ + +#define HLIST_HEAD_INIT { .first = NULL } +#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL } +#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL) +#define INIT_HLIST_NODE hlist_init +static inline void hlist_init(struct hlist_node *h) +{ + h->next = NULL; + h->pprev = NULL; +} + +static inline int hlist_unhashed(const struct hlist_node *h) +{ + return !h->pprev; +} + +static inline int hlist_empty(const struct hlist_head *h) +{ + return !h->first; +} + +static inline void __hlist_del(struct hlist_node *n) +{ + struct hlist_node *next = n->next; + struct hlist_node **pprev = n->pprev; + *pprev = next; + if (next) + next->pprev = pprev; +} + +static inline void hlist_del(struct hlist_node *n) +{ + __hlist_del(n); + //n->next = NULL; + //n->pprev = NULL; +} + +static inline void hlist_del_init(struct hlist_node *n) +{ + if (!hlist_unhashed(n)) { + __hlist_del(n); + INIT_HLIST_NODE(n); + } +} + +static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +{ + struct hlist_node *first = h->first; + n->next = first; + if (first) + first->pprev = &n->next; + h->first = n; + n->pprev = &h->first; +} + +/* next must be != NULL */ +static inline void hlist_add_before(struct hlist_node *n, + struct hlist_node *next) +{ + n->pprev = next->pprev; + n->next = next; + next->pprev = &n->next; + *(n->pprev) = n; +} + +static inline void hlist_add_after(struct hlist_node *n, + struct hlist_node *next) +{ + next->next = n->next; + n->next = next; + next->pprev = &n->next; + + if(next->next) + next->next->pprev = &next->next; +} + +/* after that we'll appear to be on some hlist and hlist_del will work */ +static inline void hlist_add_fake(struct hlist_node *n) +{ + n->pprev = &n->next; +} + +/* + * Move a list from one list head to another. Fixup the pprev + * reference of the first entry if it exists. + */ +static inline void hlist_move_list(struct hlist_head *old, + struct hlist_head *n) +{ + n->first = old->first; + if (n->first) + n->first->pprev = &n->first; + old->first = NULL; +} + +#define hlist_entry(ptr, type, member) container_of(ptr,type,member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ + pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ + pos = n) + +/** + * hlist_for_each_entry - iterate over list of given type + * @tpos: the type * to use as a loop cursor. + * @pos: the &struct hlist_node to use as a loop cursor. + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry(tpos, pos, head, member) \ + for (pos = (head)->first; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_continue - iterate over a hlist continuing after current point + * @tpos: the type * to use as a loop cursor. + * @pos: the &struct hlist_node to use as a loop cursor. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_continue(tpos, pos, member) \ + for (pos = (pos)->next; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_from - iterate over a hlist continuing from current point + * @tpos: the type * to use as a loop cursor. + * @pos: the &struct hlist_node to use as a loop cursor. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_from(tpos, pos, member) \ + for (; pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @tpos: the type * to use as a loop cursor. + * @pos: the &struct hlist_node to use as a loop cursor. + * @n: another &struct hlist_node to use as temporary storage + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ + for (pos = (head)->first; \ + pos && ({ n = pos->next; 1; }) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = n) + +#endif diff --git a/external/libhv/libhv-1.3.2/base/netinet.h b/external/libhv/libhv-1.3.2/base/netinet.h new file mode 100644 index 0000000..4969639 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/netinet.h @@ -0,0 +1,194 @@ +#ifndef HV_NETINET_H_ +#define HV_NETINET_H_ + +#include "hplatform.h" + +/* +#ifdef OS_UNIX +#include +#include +#include +#include +#include +typedef struct iphdr iphdr_t; +typedef struct udphdr udphdr_t; +typedef struct tcphdr tcphdr_t; + +typedef struct icmphdr icmphdr_t; +typedef struct icmp icmp_t; +#else +*/ +// sizeof(iphdr_t) = 20 +typedef struct iphdr_s { +#if BYTE_ORDER == LITTLE_ENDIAN + uint8_t ihl:4; // ip header length + uint8_t version:4; +#elif BYTE_ORDER == BIG_ENDIAN + uint8_t version:4; + uint8_t ihl:4; +#else +#error "BYTE_ORDER undefined!" +#endif + uint8_t tos; // type of service + uint16_t tot_len; // total length + uint16_t id; + uint16_t frag_off; // fragment offset + uint8_t ttl; // Time To Live + uint8_t protocol; + uint16_t check; // checksum + uint32_t saddr; // srcaddr + uint32_t daddr; // dstaddr + /*The options start here.*/ +} iphdr_t; + +// sizeof(udphdr_t) = 8 +typedef struct udphdr_s { + uint16_t source; // source port + uint16_t dest; // dest port + uint16_t len; // udp length + uint16_t check; // checksum +} udphdr_t; + +// sizeof(tcphdr_t) = 20 +typedef struct tcphdr_s { + uint16_t source; // source port + uint16_t dest; // dest port + uint32_t seq; // sequence + uint32_t ack_seq; +#if BYTE_ORDER == LITTLE_ENDIAN + uint16_t res1:4; + uint16_t doff:4; + uint16_t fin:1; + uint16_t syn:1; + uint16_t rst:1; + uint16_t psh:1; + uint16_t ack:1; + uint16_t urg:1; + uint16_t res2:2; +#elif BYTE_ORDER == BIG_ENDIAN + uint16_t doff:4; + uint16_t res1:4; + uint16_t res2:2; + uint16_t urg:1; + uint16_t ack:1; + uint16_t psh:1; + uint16_t rst:1; + uint16_t syn:1; + uint16_t fin:1; +#else +#error "BYTE_ORDER undefined!" +#endif + uint16_t window; + uint16_t check; // checksum + uint16_t urg_ptr; // urgent pointer +} tcphdr_t; + +//----------------------icmp---------------------------------- +#define ICMP_ECHOREPLY 0 /* Echo Reply */ +#define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ +#define ICMP_SOURCE_QUENCH 4 /* Source Quench */ +#define ICMP_REDIRECT 5 /* Redirect (change route) */ +#define ICMP_ECHO 8 /* Echo Request */ +#define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ +#define ICMP_PARAMETERPROB 12 /* Parameter Problem */ +#define ICMP_TIMESTAMP 13 /* Timestamp Request */ +#define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ +#define ICMP_INFO_REQUEST 15 /* Information Request */ +#define ICMP_INFO_REPLY 16 /* Information Reply */ +#define ICMP_ADDRESS 17 /* Address Mask Request */ +#define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ + +// sizeof(icmphdr_t) = 8 +typedef struct icmphdr_s { + uint8_t type; // message type + uint8_t code; // type sub-code + uint16_t checksum; + union { + struct { + uint16_t id; + uint16_t sequence; + } echo; + uint32_t gateway; + struct { + uint16_t reserved; + uint16_t mtu; + } frag; + } un; +} icmphdr_t; + +typedef struct icmp_s { + uint8_t icmp_type; + uint8_t icmp_code; + uint16_t icmp_cksum; + union { + uint8_t ih_pptr; + struct in_addr ih_gwaddr; + struct ih_idseq { + uint16_t icd_id; + uint16_t icd_seq; + } ih_idseq; + uint32_t ih_void; + + struct ih_pmtu { + uint16_t ipm_void; + uint16_t ipm_nextmtu; + } ih_pmtu; + + struct ih_rtradv { + uint8_t irt_num_addrs; + uint8_t irt_wpa; + uint16_t irt_lifetime; + } ih_rtradv; + } icmp_hun; +#define icmp_pptr icmp_hun.ih_pptr +#define icmp_gwaddr icmp_hun.ih_gwaddr +#define icmp_id icmp_hun.ih_idseq.icd_id +#define icmp_seq icmp_hun.ih_idseq.icd_seq +#define icmp_void icmp_hun.ih_void +#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void +#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu +#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs +#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa +#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime + + union { + struct { + uint32_t its_otime; + uint32_t its_rtime; + uint32_t its_ttime; + } id_ts; + /* + struct { + struct ip idi_ip; + } id_ip; + struct icmp_ra_addr id_radv; + */ + uint32_t id_mask; + uint8_t id_data[1]; + } icmp_dun; +#define icmp_otime icmp_dun.id_ts.its_otime +#define icmp_rtime icmp_dun.id_ts.its_rtime +#define icmp_ttime icmp_dun.id_ts.its_ttime +#define icmp_ip icmp_dun.id_ip.idi_ip +#define icmp_radv icmp_dun.id_radv +#define icmp_mask icmp_dun.id_mask +#define icmp_data icmp_dun.id_data +} icmp_t; +//#endif + +static inline uint16_t checksum(uint8_t* buf, int len) { + unsigned int sum = 0; + uint16_t* ptr = (uint16_t*)buf; + while(len > 1) { + sum += *ptr++; + len -= 2; + } + if(len) { + sum += *(uint8_t*)ptr; + } + sum = (sum >> 16) + (sum & 0xffff); + sum += (sum >> 16); + return (uint16_t)(~sum); +}; + +#endif // HV_NETINET_H_ diff --git a/external/libhv/libhv-1.3.2/base/queue.h b/external/libhv/libhv-1.3.2/base/queue.h new file mode 100644 index 0000000..17140a9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/queue.h @@ -0,0 +1,105 @@ +#ifndef HV_QUEUE_H_ +#define HV_QUEUE_H_ + +/* + * queue + * FIFO: push_back,pop_front + * stack + * LIFO: push_back,pop_back + */ + +#include // for assert +#include // for NULL +#include // for malloc,realloc,free +#include // for memset,memmove + +#include "hbase.h" // for HV_ALLOC, HV_FREE + +#define QUEUE_INIT_SIZE 16 + +// #include +// typedef std::deque qtype; +#define QUEUE_DECL(type, qtype) \ +struct qtype { \ + type* ptr; \ + size_t size; \ + size_t maxsize;\ + size_t _offset;\ +}; \ +typedef struct qtype qtype;\ +\ +static inline type* qtype##_data(qtype* p) {\ + return p->ptr + p->_offset;\ +}\ +\ +static inline int qtype##_size(qtype* p) {\ + return p->size;\ +}\ +\ +static inline int qtype##_maxsize(qtype* p) {\ + return p->maxsize;\ +}\ +\ +static inline int qtype##_empty(qtype* p) {\ + return p->size == 0;\ +}\ +\ +static inline type* qtype##_front(qtype* p) {\ + return p->size == 0 ? NULL : p->ptr + p->_offset;\ +}\ +\ +static inline type* qtype##_back(qtype* p) {\ + return p->size == 0 ? NULL : p->ptr + p->_offset + p->size - 1;\ +}\ +\ +static inline void qtype##_init(qtype* p, int maxsize) {\ + p->_offset = 0;\ + p->size = 0;\ + p->maxsize = maxsize;\ + HV_ALLOC(p->ptr, sizeof(type) * maxsize);\ +}\ +\ +static inline void qtype##_clear(qtype* p) {\ + p->_offset = 0;\ + p->size = 0;\ + memset(p->ptr, 0, sizeof(type) * p->maxsize);\ +}\ +\ +static inline void qtype##_cleanup(qtype* p) {\ + HV_FREE(p->ptr);\ + p->_offset = p->size = p->maxsize = 0;\ +}\ +\ +static inline void qtype##_resize(qtype* p, int maxsize) {\ + if (maxsize == 0) maxsize = QUEUE_INIT_SIZE;\ + p->ptr = (type*)hv_realloc(p->ptr, sizeof(type) * maxsize, sizeof(type) * p->maxsize);\ + p->maxsize = maxsize;\ +}\ +\ +static inline void qtype##_double_resize(qtype* p) {\ + qtype##_resize(p, p->maxsize * 2);\ +}\ +\ +static inline void qtype##_push_back(qtype* p, type* elem) {\ + if (p->size == p->maxsize) {\ + qtype##_double_resize(p);\ + }\ + else if (p->_offset + p->size == p->maxsize) {\ + memmove(p->ptr, p->ptr + p->_offset, sizeof(type) * p->size);\ + p->_offset = 0;\ + }\ + p->ptr[p->_offset + p->size] = *elem;\ + p->size++;\ +}\ +static inline void qtype##_pop_front(qtype* p) {\ + assert(p->size > 0);\ + p->size--;\ + if (++p->_offset == p->maxsize) p->_offset = 0;\ +}\ +\ +static inline void qtype##_pop_back(qtype* p) {\ + assert(p->size > 0);\ + p->size--;\ +}\ + +#endif // HV_QUEUE_H_ diff --git a/external/libhv/libhv-1.3.2/base/rbtree.c b/external/libhv/libhv-1.3.2/base/rbtree.c new file mode 100644 index 0000000..9998f23 --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/rbtree.c @@ -0,0 +1,386 @@ +/* + Red Black Trees + (C) 1999 Andrea Arcangeli + (C) 2002 David Woodhouse + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + linux/lib/rbtree.c +*/ + +#include "rbtree.h" + +static void __rb_rotate_left(struct rb_node *node, struct rb_root *root) +{ + struct rb_node *right = node->rb_right; + + if ((node->rb_right = right->rb_left)) + right->rb_left->rb_parent = node; + right->rb_left = node; + + if ((right->rb_parent = node->rb_parent)) + { + if (node == node->rb_parent->rb_left) + node->rb_parent->rb_left = right; + else + node->rb_parent->rb_right = right; + } + else + root->rb_node = right; + node->rb_parent = right; +} + +static void __rb_rotate_right(struct rb_node *node, struct rb_root *root) +{ + struct rb_node *left = node->rb_left; + + if ((node->rb_left = left->rb_right)) + left->rb_right->rb_parent = node; + left->rb_right = node; + + if ((left->rb_parent = node->rb_parent)) + { + if (node == node->rb_parent->rb_right) + node->rb_parent->rb_right = left; + else + node->rb_parent->rb_left = left; + } + else + root->rb_node = left; + node->rb_parent = left; +} + +void rb_insert_color(struct rb_node *node, struct rb_root *root) +{ + struct rb_node *parent, *gparent; + + while ((parent = node->rb_parent) && parent->rb_color == RB_RED) + { + gparent = parent->rb_parent; + + if (parent == gparent->rb_left) + { + { + register struct rb_node *uncle = gparent->rb_right; + if (uncle && uncle->rb_color == RB_RED) + { + uncle->rb_color = RB_BLACK; + parent->rb_color = RB_BLACK; + gparent->rb_color = RB_RED; + node = gparent; + continue; + } + } + + if (parent->rb_right == node) + { + register struct rb_node *tmp; + __rb_rotate_left(parent, root); + tmp = parent; + parent = node; + node = tmp; + } + + parent->rb_color = RB_BLACK; + gparent->rb_color = RB_RED; + __rb_rotate_right(gparent, root); + } else { + { + register struct rb_node *uncle = gparent->rb_left; + if (uncle && uncle->rb_color == RB_RED) + { + uncle->rb_color = RB_BLACK; + parent->rb_color = RB_BLACK; + gparent->rb_color = RB_RED; + node = gparent; + continue; + } + } + + if (parent->rb_left == node) + { + register struct rb_node *tmp; + __rb_rotate_right(parent, root); + tmp = parent; + parent = node; + node = tmp; + } + + parent->rb_color = RB_BLACK; + gparent->rb_color = RB_RED; + __rb_rotate_left(gparent, root); + } + } + + root->rb_node->rb_color = RB_BLACK; +} + +static void __rb_erase_color(struct rb_node *node, struct rb_node *parent, + struct rb_root *root) +{ + struct rb_node *other; + + while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node) + { + if (parent->rb_left == node) + { + other = parent->rb_right; + if (other->rb_color == RB_RED) + { + other->rb_color = RB_BLACK; + parent->rb_color = RB_RED; + __rb_rotate_left(parent, root); + other = parent->rb_right; + } + if ((!other->rb_left || + other->rb_left->rb_color == RB_BLACK) + && (!other->rb_right || + other->rb_right->rb_color == RB_BLACK)) + { + other->rb_color = RB_RED; + node = parent; + parent = node->rb_parent; + } + else + { + if (!other->rb_right || + other->rb_right->rb_color == RB_BLACK) + { + register struct rb_node *o_left; + if ((o_left = other->rb_left)) + o_left->rb_color = RB_BLACK; + other->rb_color = RB_RED; + __rb_rotate_right(other, root); + other = parent->rb_right; + } + other->rb_color = parent->rb_color; + parent->rb_color = RB_BLACK; + if (other->rb_right) + other->rb_right->rb_color = RB_BLACK; + __rb_rotate_left(parent, root); + node = root->rb_node; + break; + } + } + else + { + other = parent->rb_left; + if (other->rb_color == RB_RED) + { + other->rb_color = RB_BLACK; + parent->rb_color = RB_RED; + __rb_rotate_right(parent, root); + other = parent->rb_left; + } + if ((!other->rb_left || + other->rb_left->rb_color == RB_BLACK) + && (!other->rb_right || + other->rb_right->rb_color == RB_BLACK)) + { + other->rb_color = RB_RED; + node = parent; + parent = node->rb_parent; + } + else + { + if (!other->rb_left || + other->rb_left->rb_color == RB_BLACK) + { + register struct rb_node *o_right; + if ((o_right = other->rb_right)) + o_right->rb_color = RB_BLACK; + other->rb_color = RB_RED; + __rb_rotate_left(other, root); + other = parent->rb_left; + } + other->rb_color = parent->rb_color; + parent->rb_color = RB_BLACK; + if (other->rb_left) + other->rb_left->rb_color = RB_BLACK; + __rb_rotate_right(parent, root); + node = root->rb_node; + break; + } + } + } + if (node) + node->rb_color = RB_BLACK; +} + +void rb_erase(struct rb_node *node, struct rb_root *root) +{ + struct rb_node *child, *parent; + int color; + + if (!node->rb_left) + child = node->rb_right; + else if (!node->rb_right) + child = node->rb_left; + else + { + struct rb_node *old = node, *left; + + node = node->rb_right; + while ((left = node->rb_left)) + node = left; + child = node->rb_right; + parent = node->rb_parent; + color = node->rb_color; + + if (child) + child->rb_parent = parent; + if (parent) + { + if (parent->rb_left == node) + parent->rb_left = child; + else + parent->rb_right = child; + } + else + root->rb_node = child; + + if (node->rb_parent == old) + parent = node; + node->rb_parent = old->rb_parent; + node->rb_color = old->rb_color; + node->rb_right = old->rb_right; + node->rb_left = old->rb_left; + + if (old->rb_parent) + { + if (old->rb_parent->rb_left == old) + old->rb_parent->rb_left = node; + else + old->rb_parent->rb_right = node; + } else + root->rb_node = node; + + old->rb_left->rb_parent = node; + if (old->rb_right) + old->rb_right->rb_parent = node; + goto color; + } + + parent = node->rb_parent; + color = node->rb_color; + + if (child) + child->rb_parent = parent; + if (parent) + { + if (parent->rb_left == node) + parent->rb_left = child; + else + parent->rb_right = child; + } + else + root->rb_node = child; + + color: + if (color == RB_BLACK) + __rb_erase_color(child, parent, root); +} + +/* + * This function returns the first node (in sort order) of the tree. + */ +struct rb_node *rb_first(struct rb_root *root) +{ + struct rb_node *n; + + n = root->rb_node; + if (!n) + return (struct rb_node *)0; + while (n->rb_left) + n = n->rb_left; + return n; +} + +struct rb_node *rb_last(struct rb_root *root) +{ + struct rb_node *n; + + n = root->rb_node; + if (!n) + return (struct rb_node *)0; + while (n->rb_right) + n = n->rb_right; + return n; +} + +struct rb_node *rb_next(struct rb_node *node) +{ + /* If we have a right-hand child, go down and then left as far + as we can. */ + if (node->rb_right) { + node = node->rb_right; + while (node->rb_left) + node = node->rb_left; + return node; + } + + /* No right-hand children. Everything down and left is + smaller than us, so any 'next' node must be in the general + direction of our parent. Go up the tree; any time the + ancestor is a right-hand child of its parent, keep going + up. First time it's a left-hand child of its parent, said + parent is our 'next' node. */ + while (node->rb_parent && node == node->rb_parent->rb_right) + node = node->rb_parent; + + return node->rb_parent; +} + +struct rb_node *rb_prev(struct rb_node *node) +{ + /* If we have a left-hand child, go down and then right as far + as we can. */ + if (node->rb_left) { + node = node->rb_left; + while (node->rb_right) + node = node->rb_right; + return node; + } + + /* No left-hand children. Go up till we find an ancestor which + is a right-hand child of its parent */ + while (node->rb_parent && node == node->rb_parent->rb_left) + node = node->rb_parent; + + return node->rb_parent; +} + +void rb_replace_node(struct rb_node *victim, struct rb_node *newnode, + struct rb_root *root) +{ + struct rb_node *parent = victim->rb_parent; + + /* Set the surrounding nodes to point to the replacement */ + if (parent) { + if (victim == parent->rb_left) + parent->rb_left = newnode; + else + parent->rb_right = newnode; + } else { + root->rb_node = newnode; + } + if (victim->rb_left) + victim->rb_left->rb_parent = newnode; + if (victim->rb_right) + victim->rb_right->rb_parent = newnode; + + /* Copy the pointers/colour from the victim to the replacement */ + *newnode = *victim; +} diff --git a/external/libhv/libhv-1.3.2/base/rbtree.h b/external/libhv/libhv-1.3.2/base/rbtree.h new file mode 100644 index 0000000..602390a --- /dev/null +++ b/external/libhv/libhv-1.3.2/base/rbtree.h @@ -0,0 +1,147 @@ +/* + Red Black Trees + (C) 1999 Andrea Arcangeli + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + linux/include/linux/rbtree.h + + To use rbtrees you'll have to implement your own insert and search cores. + This will avoid us to use callbacks and to drop drammatically performances. + I know it's not the cleaner way, but in C (not in C++) to get + performances and genericity... + + Some example of insert and search follows here. The search is a plain + normal search over an ordered tree. The insert instead must be implemented + in two steps: First, the code must insert the element in order as a red leaf + in the tree, and then the support library function rb_insert_color() must + be called. Such function will do the not trivial work to rebalance the + rbtree, if necessary. + +----------------------------------------------------------------------- +static inline struct page * rb_search_page_cache(struct inode * inode, + unsigned long offset) +{ + struct rb_node * n = inode->i_rb_page_cache.rb_node; + struct page * page; + + while (n) + { + page = rb_entry(n, struct page, rb_page_cache); + + if (offset < page->offset) + n = n->rb_left; + else if (offset > page->offset) + n = n->rb_right; + else + return page; + } + return NULL; +} + +static inline struct page * __rb_insert_page_cache(struct inode * inode, + unsigned long offset, + struct rb_node * node) +{ + struct rb_node ** p = &inode->i_rb_page_cache.rb_node; + struct rb_node * parent = NULL; + struct page * page; + + while (*p) + { + parent = *p; + page = rb_entry(parent, struct page, rb_page_cache); + + if (offset < page->offset) + p = &(*p)->rb_left; + else if (offset > page->offset) + p = &(*p)->rb_right; + else + return page; + } + + rb_link_node(node, parent, p); + + return NULL; +} + +static inline struct page * rb_insert_page_cache(struct inode * inode, + unsigned long offset, + struct rb_node * node) +{ + struct page * ret; + if ((ret = __rb_insert_page_cache(inode, offset, node))) + goto out; + rb_insert_color(node, &inode->i_rb_page_cache); + out: + return ret; +} +----------------------------------------------------------------------- +*/ + +#ifndef _LINUX_RBTREE_H +#define _LINUX_RBTREE_H + +struct rb_node +{ + struct rb_node *rb_parent; + struct rb_node *rb_right; + struct rb_node *rb_left; + char rb_color; +#define RB_RED 0 +#define RB_BLACK 1 +}; + +struct rb_root +{ + struct rb_node *rb_node; +}; + +#define RB_ROOT (struct rb_root){ (struct rb_node *)0, } +#define rb_entry(ptr, type, member) \ + ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member))) + +#ifdef __cplusplus +extern "C" +{ +#endif + +void rb_insert_color(struct rb_node *node, struct rb_root *root); +void rb_erase(struct rb_node *node, struct rb_root *root); + +/* Find logical next and previous nodes in a tree */ +struct rb_node *rb_next(struct rb_node *); +struct rb_node *rb_prev(struct rb_node *); +struct rb_node *rb_first(struct rb_root *); +struct rb_node *rb_last(struct rb_root *); + +/* Fast replacement of a single node without remove/rebalance/add/rebalance */ +void rb_replace_node(struct rb_node *victim, struct rb_node *newnode, + struct rb_root *root); + +#ifdef __cplusplus +} +#endif + +static inline void rb_link_node(struct rb_node *node, struct rb_node *parent, + struct rb_node **link) +{ + node->rb_parent = parent; + node->rb_color = RB_RED; + node->rb_left = node->rb_right = (struct rb_node *)0; + *link = node; +} + +#endif /* _LINUX_RBTREE_H */ diff --git a/external/libhv/libhv-1.3.2/cert/cacert.pem b/external/libhv/libhv-1.3.2/cert/cacert.pem new file mode 100644 index 0000000..65be218 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cert/cacert.pem @@ -0,0 +1,3476 @@ +## +## Bundle of CA Root Certificates +## +## Certificate data from Mozilla as of: Wed Aug 28 03:12:10 2019 GMT +## +## This is a bundle of X.509 certificates of public Certificate Authorities +## (CA). These were automatically extracted from Mozilla's root certificates +## file (certdata.txt). This file can be found in the mozilla source tree: +## https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt +## +## It contains the certificates in PEM format and therefore +## can be directly used with curl / libcurl / php_curl, or with +## an Apache+mod_ssl webserver for SSL client authentication. +## Just configure this file as the SSLCACertificateFile. +## +## Conversion done with mk-ca-bundle.pl version 1.27. +## SHA256: fffa309937c3be940649293f749b8207fabc6eb224e50e4bb3f2c5e44e0d6a6b +## + + +GlobalSign Root CA +================== +-----BEGIN CERTIFICATE----- +MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx +GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds +b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV +BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD +VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa +DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc +THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb +Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP +c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX +gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF +AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj +Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG +j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH +hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC +X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== +-----END CERTIFICATE----- + +GlobalSign Root CA - R2 +======================= +-----BEGIN CERTIFICATE----- +MIIDujCCAqKgAwIBAgILBAAAAAABD4Ym5g0wDQYJKoZIhvcNAQEFBQAwTDEgMB4GA1UECxMXR2xv +YmFsU2lnbiBSb290IENBIC0gUjIxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh +bFNpZ24wHhcNMDYxMjE1MDgwMDAwWhcNMjExMjE1MDgwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT +aWduIFJvb3QgQ0EgLSBSMjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln +bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbPJA6+Lm8omUVCxKs+IVSbC9N/hHD6 +ErPLv4dfxn+G07IwXNb9rfF73OX4YJYJkhD10FPe+3t+c4isUoh7SqbKSaZeqKeMWhG8eoLrvozp +s6yWJQeXSpkqBy+0Hne/ig+1AnwblrjFuTosvNYSuetZfeLQBoZfXklqtTleiDTsvHgMCJiEbKjN +S7SgfQx5TfC4LcshytVsW33hoCmEofnTlEnLJGKRILzdC9XZzPnqJworc5HGnRusyMvo4KD0L5CL +TfuwNhv2GXqF4G3yYROIXJ/gkwpRl4pazq+r1feqCapgvdzZX99yqWATXgAByUr6P6TqBwMhAo6C +ygPCm48CAwEAAaOBnDCBmTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E +FgQUm+IHV2ccHsBqBt5ZtJot39wZhi4wNgYDVR0fBC8wLTAroCmgJ4YlaHR0cDovL2NybC5nbG9i +YWxzaWduLm5ldC9yb290LXIyLmNybDAfBgNVHSMEGDAWgBSb4gdXZxwewGoG3lm0mi3f3BmGLjAN +BgkqhkiG9w0BAQUFAAOCAQEAmYFThxxol4aR7OBKuEQLq4GsJ0/WwbgcQ3izDJr86iw8bmEbTUsp +9Z8FHSbBuOmDAGJFtqkIk7mpM0sYmsL4h4hO291xNBrBVNpGP+DTKqttVCL1OmLNIG+6KYnX3ZHu +01yiPqFbQfXf5WRDLenVOavSot+3i9DAgBkcRcAtjOj4LaR0VknFBbVPFd5uRHg5h6h+u/N5GJG7 +9G+dwfCMNYxdAfvDbbnvRG15RjF+Cv6pgsH/76tuIMRQyV+dTZsXjAzlAcmgQWpzU/qlULRuJQ/7 +TBj0/VLZjmmx6BEP3ojY+x1J96relc8geMJgEtslQIxq/H5COEBkEveegeGTLg== +-----END CERTIFICATE----- + +Verisign Class 3 Public Primary Certification Authority - G3 +============================================================ +-----BEGIN CERTIFICATE----- +MIIEGjCCAwICEQCbfgZJoz5iudXukEhxKe9XMA0GCSqGSIb3DQEBBQUAMIHKMQswCQYDVQQGEwJV +UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv +cmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkgLSBHMzAeFw05OTEwMDEwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMIHKMQsw +CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy +dXN0IE5ldHdvcmsxOjA4BgNVBAsTMShjKSAxOTk5IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxRTBDBgNVBAMTPFZlcmlTaWduIENsYXNzIDMgUHVibGljIFByaW1hcnkg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAMu6nFL8eB8aHm8bN3O9+MlrlBIwT/A2R/XQkQr1F8ilYcEWQE37imGQ5XYgwREGfassbqb1 +EUGO+i2tKmFZpGcmTNDovFJbcCAEWNF6yaRpvIMXZK0Fi7zQWM6NjPXr8EJJC52XJ2cybuGukxUc +cLwgTS8Y3pKI6GyFVxEa6X7jJhFUokWWVYPKMIno3Nij7SqAP395ZVc+FSBmCC+Vk7+qRy+oRpfw +EuL+wgorUeZ25rdGt+INpsyow0xZVYnm6FNcHOqd8GIWC6fJXwzw3sJ2zq/3avL6QaaiMxTJ5Xpj +055iN9WFZZ4O5lMkdBteHRJTW8cs54NJOxWuimi5V5cCAwEAATANBgkqhkiG9w0BAQUFAAOCAQEA +ERSWwauSCPc/L8my/uRan2Te2yFPhpk0djZX3dAVL8WtfxUfN2JzPtTnX84XA9s1+ivbrmAJXx5f +j267Cz3qWhMeDGBvtcC1IyIuBwvLqXTLR7sdwdela8wv0kL9Sd2nic9TutoAWii/gt/4uhMdUIaC +/Y4wjylGsB49Ndo4YhYYSq3mtlFs3q9i6wHQHiT+eo8SGhJouPtmmRQURVyu565pF4ErWjfJXir0 +xuKhXFSbplQAz/DxwceYMBo7Nhbbo27q/a2ywtrvAkcTisDxszGtTxzhT5yvDwyd93gN2PQ1VoDa +t20Xj50egWTh/sVFuq1ruQp6Tk9LhO5L8X3dEQ== +-----END CERTIFICATE----- + +Entrust.net Premium 2048 Secure Server CA +========================================= +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChMLRW50cnVzdC5u +ZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBpbmNvcnAuIGJ5IHJlZi4gKGxp +bWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNV +BAMTKkVudHJ1c3QubmV0IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQx +NzUwNTFaFw0yOTA3MjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3 +d3d3LmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxpYWIuKTEl +MCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5u +ZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEArU1LqRKGsuqjIAcVFmQqK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOL +Gp18EzoOH1u3Hs/lJBQesYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSr +hRSGlVuXMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVTXTzW +nLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/HoZdenoVve8AjhUi +VBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH4QIDAQABo0IwQDAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJ +KoZIhvcNAQEFBQADggEBADubj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPy +T/4xmf3IDExoU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf +zX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5bu/8j72gZyxKT +J1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+bYQLCIt+jerXmCHG8+c8eS9e +nNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/ErfF6adulZkMV8gzURZVE= +-----END CERTIFICATE----- + +Baltimore CyberTrust Root +========================= +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJRTESMBAGA1UE +ChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYDVQQDExlCYWx0aW1vcmUgQ3li +ZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoXDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMC +SUUxEjAQBgNVBAoTCUJhbHRpbW9yZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFs +dGltb3JlIEN5YmVyVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKME +uyKrmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjrIZ3AQSsB +UnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeKmpYcqWe4PwzV9/lSEy/C +G9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSuXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9 +XbIGevOF6uvUA65ehD5f/xXtabz5OTZydc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjpr +l3RjM71oGDHweI12v/yejl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoI +VDaGezq1BE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEB +BQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT929hkTI7gQCvlYpNRh +cL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3WgxjkzSswF07r51XgdIGn9w/xZchMB5 +hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0Epn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsa +Y71k5h+3zvDyny67G7fyUIhzksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9H +RCwBXbsdtTLSR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp +-----END CERTIFICATE----- + +AddTrust External Root +====================== +-----BEGIN CERTIFICATE----- +MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEUMBIGA1UEChML +QWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYD +VQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEw +NDgzOFowbzELMAkGA1UEBhMCU0UxFDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRU +cnVzdCBFeHRlcm5hbCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0Eg +Um9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvtH7xsD821 ++iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9uMq/NzgtHj6RQa1wVsfw +Tz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzXmk6vBbOmcZSccbNQYArHE504B4YCqOmo +aSYYkKtMsE8jqzpPhNjfzp/haW+710LXa0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy +2xSoRcRdKn23tNbE7qzNE0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv7 +7+ldU9U0WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYDVR0P +BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0Jvf6xCZU7wO94CTL +VBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRk +VHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB +IFJvb3SCAQEwDQYJKoZIhvcNAQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZl +j7DYd7usQWxHYINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 +6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvCNr4TDea9Y355 +e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEXc4g/VhsxOBi0cQ+azcgOno4u +G+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5amnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= +-----END CERTIFICATE----- + +Entrust Root Certification Authority +==================================== +-----BEGIN CERTIFICATE----- +MIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMCVVMxFjAUBgNV +BAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0Lm5ldC9DUFMgaXMgaW5jb3Jw +b3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMWKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsG +A1UEAxMkRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0 +MloXDTI2MTEyNzIwNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMu +MTkwNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSByZWZlcmVu +Y2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNVBAMTJEVudHJ1c3QgUm9v +dCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALaVtkNC+sZtKm9I35RMOVcF7sN5EUFoNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYsz +A9u3g3s+IIRe7bJWKKf44LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOww +Cj0Yzfv9KlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGIrb68 +j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi94DkZfs0Nw4pgHBN +rziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOBsDCBrTAOBgNVHQ8BAf8EBAMCAQYw +DwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAigA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1 +MzQyWjAfBgNVHSMEGDAWgBRokORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DH +hmak8fdLQ/uEvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA +A4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9tO1KzKtvn1ISM +Y/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6ZuaAGAT/3B+XxFNSRuzFVJ7yVTa +v52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTS +W3iDVuycNsMm4hH2Z0kdkquM++v/eu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0 +tHuu2guQOHXvgR1m0vdXcDazv/wor3ElhVsT/h5/WrQ8 +-----END CERTIFICATE----- + +GeoTrust Global CA +================== +-----BEGIN CERTIFICATE----- +MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVTMRYwFAYDVQQK +Ew1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9iYWwgQ0EwHhcNMDIwNTIxMDQw +MDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5j +LjEbMBkGA1UEAxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjo +BbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDviS2Aelet +8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU1XupGc1V3sjs0l44U+Vc +T4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagU +vTLrGAMoUgRx5aszPeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVk +DBF9qn1luMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKInZ57Q +zxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfStQWVYrmm3ok9Nns4 +d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcFPseKUgzbFbS9bZvlxrFUaKnjaZC2 +mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Unhw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6p +XE0zX5IJL4hmXXeXxx12E6nV5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvm +Mw== +-----END CERTIFICATE----- + +GeoTrust Universal CA +===================== +-----BEGIN CERTIFICATE----- +MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN +R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVyc2FsIENBMB4XDTA0MDMwNDA1 +MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu +Yy4xHjAcBgNVBAMTFUdlb1RydXN0IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIP +ADCCAgoCggIBAKYVVaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9t +JPi8cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTTQjOgNB0e +RXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFhF7em6fgemdtzbvQKoiFs +7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2vc7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d +8Lsrlh/eezJS/R27tQahsiFepdaVaH/wmZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7V +qnJNk22CDtucvc+081xdVHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3Cga +Rr0BHdCXteGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZf9hB +Z3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfReBi9Fi1jUIxaS5BZu +KGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+nhutxx9z3SxPGWX9f5NAEC7S8O08 +ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0 +XG0D08DYj3rWMB8GA1UdIwQYMBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIB +hjANBgkqhkiG9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc +aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fXIwjhmF7DWgh2 +qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzynANXH/KttgCJwpQzgXQQpAvvL +oJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0zuzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsK +xr2EoyNB3tZ3b4XUhRxQ4K5RirqNPnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxF +KyDuSN/n3QmOGKjaQI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2 +DFKWkoRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9ER/frslK +xfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQtDF4JbAiXfKM9fJP/P6EU +p8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/SfuvmbJxPgWp6ZKy7PtXny3YuxadIwVyQD8vI +P/rmMuGNG2+k5o7Y+SlIis5z/iw= +-----END CERTIFICATE----- + +GeoTrust Universal CA 2 +======================= +-----BEGIN CERTIFICATE----- +MIIFbDCCA1SgAwIBAgIBATANBgkqhkiG9w0BAQUFADBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN +R2VvVHJ1c3QgSW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwHhcNMDQwMzA0 +MDUwMDAwWhcNMjkwMzA0MDUwMDAwWjBHMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3Qg +SW5jLjEgMB4GA1UEAxMXR2VvVHJ1c3QgVW5pdmVyc2FsIENBIDIwggIiMA0GCSqGSIb3DQEBAQUA +A4ICDwAwggIKAoICAQCzVFLByT7y2dyxUxpZKeexw0Uo5dfR7cXFS6GqdHtXr0om/Nj1XqduGdt0 +DE81WzILAePb63p3NeqqWuDW6KFXlPCQo3RWlEQwAx5cTiuFJnSCegx2oG9NzkEtoBUGFF+3Qs17 +j1hhNNwqCPkuwwGmIkQcTAeC5lvO0Ep8BNMZcyfwqph/Lq9O64ceJHdqXbboW0W63MOhBW9Wjo8Q +JqVJwy7XQYci4E+GymC16qFjwAGXEHm9ADwSbSsVsaxLse4YuU6W3Nx2/zu+z18DwPw76L5GG//a +QMJS9/7jOvdqdzXQ2o3rXhhqMcceujwbKNZrVMaqW9eiLBsZzKIC9ptZvTdrhrVtgrrY6slWvKk2 +WP0+GfPtDCapkzj4T8FdIgbQl+rhrcZV4IErKIM6+vR7IVEAvlI4zs1meaj0gVbi0IMJR1FbUGrP +20gaXT73y/Zl92zxlfgCOzJWgjl6W70viRu/obTo/3+NjN8D8WBOWBFM66M/ECuDmgFz2ZRthAAn +ZqzwcEAJQpKtT5MNYQlRJNiS1QuUYbKHsu3/mjX/hVTK7URDrBs8FmtISgocQIgfksILAAX/8sgC +SqSqqcyZlpwvWOB94b67B9xfBHJcMTTD7F8t4D1kkCLm0ey4Lt1ZrtmhN79UNdxzMk+MBB4zsslG +8dhcyFVQyWi9qLo2CQIDAQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR281Xh+qQ2 ++/CfXGJx7Tz0RzgQKzAfBgNVHSMEGDAWgBR281Xh+qQ2+/CfXGJx7Tz0RzgQKzAOBgNVHQ8BAf8E +BAMCAYYwDQYJKoZIhvcNAQEFBQADggIBAGbBxiPz2eAubl/oz66wsCVNK/g7WJtAJDday6sWSf+z +dXkzoS9tcBc0kf5nfo/sm+VegqlVHy/c1FEHEv6sFj4sNcZj/NwQ6w2jqtB8zNHQL1EuxBRa3ugZ +4T7GzKQp5y6EqgYweHZUcyiYWTjgAA1i00J9IZ+uPTqM1fp3DRgrFg5fNuH8KrUwJM/gYwx7WBr+ +mbpCErGR9Hxo4sjoryzqyX6uuyo9DRXcNJW2GHSoag/HtPQTxORb7QrSpJdMKu0vbBKJPfEncKpq +A1Ihn0CoZ1Dy81of398j9tx4TuaYT1U6U+Pv8vSfx3zYWK8pIpe44L2RLrB27FcRz+8pRPPphXpg +Y+RdM4kX2TGq2tbzGDVyz4crL2MjhF2EjD9XoIj8mZEoJmmZ1I+XRL6O1UixpCgp8RW04eWe3fiP +pm8m1wk8OhwRDqZsN/etRIcsKMfYdIKz0G9KV7s1KSegi+ghp4dkNl3M2Basx7InQJJVOCiNUW7d +FGdTbHFcJoRNdVq2fmBWqU2t+5sel/MN2dKXVHfaPRK34B7vCAas+YWH6aLcr34YEoP9VhdBLtUp +gn2Z9DH2canPLAEnpQW5qrJITirvn5NSUZU8UnOOVkwXQMAJKOSLakhT2+zNVVXxxvjpoixMptEm +X36vWkzaH6byHCx+rgIW0lbQL1dTR+iS +-----END CERTIFICATE----- + +Comodo AAA Services root +======================== +-----BEGIN CERTIFICATE----- +MIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEbMBkGA1UECAwS +R3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRowGAYDVQQKDBFDb21vZG8gQ0Eg +TGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmljYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAw +MFoXDTI4MTIzMTIzNTk1OVowezELMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hl +c3RlcjEQMA4GA1UEBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNV +BAMMGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQuaBtDFcCLNSS1UY8y2bmhG +C1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe3M/vg4aijJRPn2jymJBGhCfHdr/jzDUs +i14HZGWCwEiwqJH5YZ92IFCokcdmtet4YgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszW +Y19zjNoFmag4qMsXeDZRrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjH +Ypy+g8cmez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQUoBEK +Iz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wewYDVR0f +BHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20vQUFBQ2VydGlmaWNhdGVTZXJ2aWNl +cy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29tb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2Vz +LmNybDANBgkqhkiG9w0BAQUFAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm +7l3sAg9g1o1QGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz +Rt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2G9w84FoVxp7Z +8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsil2D4kF501KKaU73yqWjgom7C +12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3smPi9WIsgtRqAEFQ8TmDn5XpNpaYbg== +-----END CERTIFICATE----- + +QuoVadis Root CA +================ +-----BEGIN CERTIFICATE----- +MIIF0DCCBLigAwIBAgIEOrZQizANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJCTTEZMBcGA1UE +ChMQUXVvVmFkaXMgTGltaXRlZDElMCMGA1UECxMcUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0 +eTEuMCwGA1UEAxMlUXVvVmFkaXMgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wMTAz +MTkxODMzMzNaFw0yMTAzMTcxODMzMzNaMH8xCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRp +cyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MS4wLAYDVQQD +EyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAv2G1lVO6V/z68mcLOhrfEYBklbTRvM16z/Ypli4kVEAkOPcahdxYTMuk +J0KX0J+DisPkBgNbAKVRHnAEdOLB1Dqr1607BxgFjv2DrOpm2RgbaIr1VxqYuvXtdj182d6UajtL +F8HVj71lODqV0D1VNk7feVcxKh7YWWVJWCCYfqtffp/p1k3sg3Spx2zY7ilKhSoGFPlU5tPaZQeL +YzcS19Dsw3sgQUSj7cugF+FxZc4dZjH3dgEZyH0DWLaVSR2mEiboxgx24ONmy+pdpibu5cxfvWen +AScOospUxbF6lR1xHkopigPcakXBpBlebzbNw6Kwt/5cOOJSvPhEQ+aQuwIDAQABo4ICUjCCAk4w +PQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwczovL29jc3AucXVvdmFkaXNvZmZzaG9y +ZS5jb20wDwYDVR0TAQH/BAUwAwEB/zCCARoGA1UdIASCAREwggENMIIBCQYJKwYBBAG+WAABMIH7 +MIHUBggrBgEFBQcCAjCBxxqBxFJlbGlhbmNlIG9uIHRoZSBRdW9WYWRpcyBSb290IENlcnRpZmlj +YXRlIGJ5IGFueSBwYXJ0eSBhc3N1bWVzIGFjY2VwdGFuY2Ugb2YgdGhlIHRoZW4gYXBwbGljYWJs +ZSBzdGFuZGFyZCB0ZXJtcyBhbmQgY29uZGl0aW9ucyBvZiB1c2UsIGNlcnRpZmljYXRpb24gcHJh +Y3RpY2VzLCBhbmQgdGhlIFF1b1ZhZGlzIENlcnRpZmljYXRlIFBvbGljeS4wIgYIKwYBBQUHAgEW +Fmh0dHA6Ly93d3cucXVvdmFkaXMuYm0wHQYDVR0OBBYEFItLbe3TKbkGGew5Oanwl4Rqy+/fMIGu +BgNVHSMEgaYwgaOAFItLbe3TKbkGGew5Oanwl4Rqy+/foYGEpIGBMH8xCzAJBgNVBAYTAkJNMRkw +FwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMSUwIwYDVQQLExxSb290IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MS4wLAYDVQQDEyVRdW9WYWRpcyBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggQ6 +tlCLMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAitQUtf70mpKnGdSkfnIYj9lo +fFIk3WdvOXrEql494liwTXCYhGHoG+NpGA7O+0dQoE7/8CQfvbLO9Sf87C9TqnN7Az10buYWnuul +LsS/VidQK2K6vkscPFVcQR0kvoIgR13VRH56FmjffU1RcHhXHTMe/QKZnAzNCgVPx7uOpHX6Sm2x +gI4JVrmcGmD+XcHXetwReNDWXcG31a0ymQM6isxUJTkxgXsTIlG6Rmyhu576BGxJJnSP0nPrzDCi +5upZIof4l/UO/erMkqQWxFIY6iHOsfHmhIHluqmGKPJDWl0Snawe2ajlCmqnf6CHKc/yiU3U7MXi +5nrQNiOKSnQ2+Q== +-----END CERTIFICATE----- + +QuoVadis Root CA 2 +================== +-----BEGIN CERTIFICATE----- +MIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT +EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMjAeFw0wNjExMjQx +ODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQCaGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6 +XJxgFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55JWpzmM+Yk +lvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bBrrcCaoF6qUWD4gXmuVbB +lDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp+ARz8un+XJiM9XOva7R+zdRcAitMOeGy +lZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1ksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt +66/3FsvbzSUr5R/7mp/iUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1Jdxn +wQ5hYIizPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og/zOh +D7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UHoycR7hYQe7xFSkyy +BNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuIyV77zGHcizN300QyNQliBJIWENie +J0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1Ud +DgQWBBQahGK8SEwzJQTU7tD2A8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGU +a6FJpEcwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT +ElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2fBluornFdLwUv +Z+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzng/iN/Ae42l9NLmeyhP3ZRPx3 +UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2BlfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodm +VjB3pjd4M1IQWK4/YY7yarHvGH5KWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK ++JDSV6IZUaUtl0HaB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrW +IozchLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPRTUIZ3Ph1 +WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWDmbA4CD/pXvk1B+TJYm5X +f6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0ZohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II +4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8 +VCLAAVBpQ570su9t+Oza8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u +-----END CERTIFICATE----- + +QuoVadis Root CA 3 +================== +-----BEGIN CERTIFICATE----- +MIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0xGTAXBgNVBAoT +EFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJvb3QgQ0EgMzAeFw0wNjExMjQx +OTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM +aW1pdGVkMRswGQYDVQQDExJRdW9WYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDMV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNgg +DhoB4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUrH556VOij +KTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd8lyyBTNvijbO0BNO/79K +DDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9CabwvvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbv +BNDInIjbC3uBr7E9KsRlOni27tyAsdLTmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwp +p5ijJUMv7/FfJuGITfhebtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8 +nT8KKdjcT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDtWAEX +MJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZc6tsgLjoC2SToJyM +Gf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A4iLItLRkT9a6fUg+qGkM17uGcclz +uD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYDVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHT +BgkrBgEEAb5YAAMwgcUwgZMGCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmlj +YXRlIGNvbnN0aXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0 +aWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVudC4wLQYIKwYB +BQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2NwczALBgNVHQ8EBAMCAQYwHQYD +VR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4GA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4 +ywLQoUmkRzBFMQswCQYDVQQGEwJCTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UE +AxMSUXVvVmFkaXMgUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZV +qyM07ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSemd1o417+s +hvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd+LJ2w/w4E6oM3kJpK27z +POuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2 +Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadNt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp +8kokUvd0/bpO5qgdAm6xDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBC +bjPsMZ57k8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6szHXu +g/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0jWy10QJLZYxkNc91p +vGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeTmJlglFwjz1onl14LBQaTNx47aTbr +qZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK4SVhM7JZG+Ju1zdXtg2pEto= +-----END CERTIFICATE----- + +Security Communication Root CA +============================== +-----BEGIN CERTIFICATE----- +MIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP +U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw +HhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5WjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMP +U0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw +8yl89f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJDKaVv0uM +DPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9Ms+k2Y7CI9eNqPPYJayX +5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/NQV3Is00qVUarH9oe4kA92819uZKAnDfd +DJZkndwi92SL32HeFZRSFaB9UslLqCHJxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2 +JChzAgMBAAGjPzA9MB0GA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYw +DwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vGkl3g +0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfrUj94nK9NrvjVT8+a +mCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5Bw+SUEmK3TGXX8npN6o7WWWXlDLJ +s58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJUJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ +6rBK+1YWc26sTfcioU+tHXotRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAi +FL39vmwLAw== +-----END CERTIFICATE----- + +Sonera Class 2 Root CA +====================== +-----BEGIN CERTIFICATE----- +MIIDIDCCAgigAwIBAgIBHTANBgkqhkiG9w0BAQUFADA5MQswCQYDVQQGEwJGSTEPMA0GA1UEChMG +U29uZXJhMRkwFwYDVQQDExBTb25lcmEgQ2xhc3MyIENBMB4XDTAxMDQwNjA3Mjk0MFoXDTIxMDQw +NjA3Mjk0MFowOTELMAkGA1UEBhMCRkkxDzANBgNVBAoTBlNvbmVyYTEZMBcGA1UEAxMQU29uZXJh +IENsYXNzMiBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJAXSjWdyvANlsdE+hY3 +/Ei9vX+ALTU74W+oZ6m/AxxNjG8yR9VBaKQTBME1DJqEQ/xcHf+Js+gXGM2RX/uJ4+q/Tl18GybT +dXnt5oTjV+WtKcT0OijnpXuENmmz/V52vaMtmdOQTiMofRhj8VQ7Jp12W5dCsv+u8E7s3TmVToMG +f+dJQMjFAbJUWmYdPfz56TwKnoG4cPABi+QjVHzIrviQHgCWctRUz2EjvOr7nQKV0ba5cTppCD8P +tOFCx4j1P5iop7oc4HFx71hXgVB6XGt0Rg6DA5jDjqhu8nYybieDwnPz3BjotJPqdURrBGAgcVeH +nfO+oJAjPYok4doh28MCAwEAAaMzMDEwDwYDVR0TAQH/BAUwAwEB/zARBgNVHQ4ECgQISqCqWITT +XjwwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBBQUAA4IBAQBazof5FnIVV0sd2ZvnoiYw7JNn39Yt +0jSv9zilzqsWuasvfDXLrNAPtEwr/IDva4yRXzZ299uzGxnq9LIR/WFxRL8oszodv7ND6J+/3DEI +cbCdjdY0RzKQxmUk96BKfARzjzlvF4xytb1LyHr4e4PDKE6cCepnP7JnBBvDFNr450kkkdAdavph +Oe9r5yF1BgfYErQhIHBCcYHaPJo2vqZbDWpsmh+Re/n570K6Tk6ezAyNlNzZRZxe7EJQY670XcSx +EtzKO6gunRRaBXW37Ndj4ro1tgQIkejanZz2ZrUYrAqmVCY0M9IbwdR/GjqOC6oybtv8TyWf2TLH +llpwrN9M +-----END CERTIFICATE----- + +XRamp Global CA Root +==================== +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCBgjELMAkGA1UE +BhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2Vj +dXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwHhcNMDQxMTAxMTcxNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMx +HjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkg +U2VydmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3Jp +dHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS638eMpSe2OAtp87ZOqCwu +IR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCPKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMx +foArtYzAQDsRhtDLooY2YKTVMIJt2W7QDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FE +zG+gSqmUsE3a56k0enI4qEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqs +AxcZZPRaJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNViPvry +xS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASsjVy16bYbMDYGA1UdHwQvMC0wK6Ap +oCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0eS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMC +AQEwDQYJKoZIhvcNAQEFBQADggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc +/Kh4ZzXxHfARvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt +qZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLaIR9NmXmd4c8n +nxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSyi6mx5O+aGtA9aZnuqCij4Tyz +8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQO+7ETPTsJ3xCwnR8gooJybQDJbw= +-----END CERTIFICATE----- + +Go Daddy Class 2 CA +=================== +-----BEGIN CERTIFICATE----- +MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMY +VGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkG +A1UEBhMCVVMxITAfBgNVBAoTGFRoZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28g +RGFkZHkgQ2xhc3MgMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQAD +ggENADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCAPVYYYwhv +2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6wwdhFJ2+qN1j3hybX2C32 +qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXiEqITLdiOr18SPaAIBQi2XKVlOARFmR6j +YGB0xUGlcmIbYsUfb18aQr4CUWWoriMYavx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmY +vLEHZ6IVDd2gWMZEewo+YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0O +BBYEFNLEsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h/t2o +atTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMu +MTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwG +A1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wim +PQoZ+YeAEW5p5JYXMP80kWNyOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKt +I3lpjbi2Tc7PTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ +HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mERdEr/VxqHD3VI +Ls9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5CufReYNnyicsbkqWletNw+vHX/b +vZ8= +-----END CERTIFICATE----- + +Starfield Class 2 CA +==================== +-----BEGIN CERTIFICATE----- +MIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzElMCMGA1UEChMc +U3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZpZWxkIENsYXNzIDIg +Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQwNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBo +MQswCQYDVQQGEwJVUzElMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAG +A1UECxMpU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqG +SIb3DQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf8MOh2tTY +bitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN+lq2cwQlZut3f+dZxkqZ +JRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0X9tDkYI22WY8sbi5gv2cOj4QyDvvBmVm +epsZGD3/cVE8MC5fvj13c7JdBmzDI1aaK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSN +F4Azbl5KXZnJHoe0nRrA1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HF +MIHCMB0GA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fRzt0f +hvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNo +bm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBDbGFzcyAyIENlcnRpZmljYXRpb24g +QXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGs +afPzWdqbAYcaT1epoXkJKtv3L7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLM +PUxA2IGvd56Deruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl +xy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynpVSJYACPq4xJD +KVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEYWQPJIrSPnNVeKtelttQKbfi3 +QBFGmh95DmK/D5fs4C8fF5Q= +-----END CERTIFICATE----- + +Taiwan GRCA +=========== +-----BEGIN CERTIFICATE----- +MIIFcjCCA1qgAwIBAgIQH51ZWtcvwgZEpYAIaeNe9jANBgkqhkiG9w0BAQUFADA/MQswCQYDVQQG +EwJUVzEwMC4GA1UECgwnR292ZXJubWVudCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4X +DTAyMTIwNTEzMjMzM1oXDTMyMTIwNTEzMjMzM1owPzELMAkGA1UEBhMCVFcxMDAuBgNVBAoMJ0dv +dmVybm1lbnQgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAJoluOzMonWoe/fOW1mKydGGEghU7Jzy50b2iPN86aXfTEc2pBsBHH8eV4qN +w8XRIePaJD9IK/ufLqGU5ywck9G/GwGHU5nOp/UKIXZ3/6m3xnOUT0b3EEk3+qhZSV1qgQdW8or5 +BtD3cCJNtLdBuTK4sfCxw5w/cP1T3YGq2GN49thTbqGsaoQkclSGxtKyyhwOeYHWtXBiCAEuTk8O +1RGvqa/lmr/czIdtJuTJV6L7lvnM4T9TjGxMfptTCAtsF/tnyMKtsc2AtJfcdgEWFelq16TheEfO +htX7MfP6Mb40qij7cEwdScevLJ1tZqa2jWR+tSBqnTuBto9AAGdLiYa4zGX+FVPpBMHWXx1E1wov +J5pGfaENda1UhhXcSTvxls4Pm6Dso3pdvtUqdULle96ltqqvKKyskKw4t9VoNSZ63Pc78/1Fm9G7 +Q3hub/FCVGqY8A2tl+lSXunVanLeavcbYBT0peS2cWeqH+riTcFCQP5nRhc4L0c/cZyu5SHKYS1t +B6iEfC3uUSXxY5Ce/eFXiGvviiNtsea9P63RPZYLhY3Naye7twWb7LuRqQoHEgKXTiCQ8P8NHuJB +O9NAOueNXdpm5AKwB1KYXA6OM5zCppX7VRluTI6uSw+9wThNXo+EHWbNxWCWtFJaBYmOlXqYwZE8 +lSOyDvR5tMl8wUohAgMBAAGjajBoMB0GA1UdDgQWBBTMzO/MKWCkO7GStjz6MmKPrCUVOzAMBgNV +HRMEBTADAQH/MDkGBGcqBwAEMTAvMC0CAQAwCQYFKw4DAhoFADAHBgVnKgMAAAQUA5vwIhP/lSg2 +09yewDL7MTqKUWUwDQYJKoZIhvcNAQEFBQADggIBAECASvomyc5eMN1PhnR2WPWus4MzeKR6dBcZ +TulStbngCnRiqmjKeKBMmo4sIy7VahIkv9Ro04rQ2JyftB8M3jh+Vzj8jeJPXgyfqzvS/3WXy6Tj +Zwj/5cAWtUgBfen5Cv8b5Wppv3ghqMKnI6mGq3ZW6A4M9hPdKmaKZEk9GhiHkASfQlK3T8v+R0F2 +Ne//AHY2RTKbxkaFXeIksB7jSJaYV0eUVXoPQbFEJPPB/hprv4j9wabak2BegUqZIJxIZhm1AHlU +D7gsL0u8qV1bYH+Mh6XgUmMqvtg7hUAV/h62ZT/FS9p+tXo1KaMuephgIqP0fSdOLeq0dDzpD6Qz +DxARvBMB1uUO07+1EqLhRSPAzAhuYbeJq4PjJB7mXQfnHyA+z2fI56wwbSdLaG5LKlwCCDTb+Hbk +Z6MmnD+iMsJKxYEYMRBWqoTvLQr/uB930r+lWKBi5NdLkXWNiYCYfm3LU05er/ayl4WXudpVBrkk +7tfGOB5jGxI7leFYrPLfhNVfmS8NVVvmONsuP3LpSIXLuykTjx44VbnzssQwmSNOXfJIoRIM3BKQ +CZBUkQM8R+XVyWXgt0t97EfTsws+rZ7QdAAO671RrcDeLMDDav7v3Aun+kbfYNucpllQdSNpc5Oy ++fwC00fmcc4QAu4njIT/rEUNE1yDMuAlpYYsfPQS +-----END CERTIFICATE----- + +DigiCert Assured ID Root CA +=========================== +-----BEGIN CERTIFICATE----- +MIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw +IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzEx +MTEwMDAwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL +ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0Ew +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7cJpSIqvTO +9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYPmDI2dsze3Tyoou9q+yHy +UmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+wRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW +/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4VYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpy +oeb6pNnVFzF1roV9Iq4/AUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whf +GHdPAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRF +66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYunpyGd823IDzANBgkq +hkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRCdWKuh+vy1dneVrOfzM4UKLkNl2Bc +EkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTffwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38Fn +SbNd67IJKusm7Xi+fT8r87cmNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i +8b5QZ7dsvfPxH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe ++o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g== +-----END CERTIFICATE----- + +DigiCert Global Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBhMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw +HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBDQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAw +MDAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 +dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkq +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsBCSDMAZOn +TjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97nh6Vfe63SKMI2tavegw5 +BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt43C/dxC//AH2hdmoRBBYMql1GNXRor5H +4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7PT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y +7vrTC0LUq7dBMtoM1O/4gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQAB +o2MwYTAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbRTLtm +8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUwDQYJKoZIhvcNAQEF +BQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/EsrhMAtudXH/vTBH1jLuG2cenTnmCmr +EbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIt +tep3Sp+dWOIrWcBAI+0tKIJFPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886 +UAb3LujEV0lsYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk +CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4= +-----END CERTIFICATE----- + +DigiCert High Assurance EV Root CA +================================== +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSsw +KQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAw +MFoXDTMxMTExMDAwMDAwMFowbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ +MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu +Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm+9S75S0t +Mqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTWPNt0OKRKzE0lgvdKpVMS +OO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3 +MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQ +NAQTXKFx01p8VdteZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUe +h10aUAsgEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMB +Af8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSY +JhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3NecnzyIZgYIVyHbIUf4KmeqvxgydkAQ +V8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6zeM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFp +myPInngiK3BD41VHMWEZ71jFhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkK +mNEVX58Svnw2Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe +vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep+OkuE6N36B9K +-----END CERTIFICATE----- + +Certplus Class 2 Primary CA +=========================== +-----BEGIN CERTIFICATE----- +MIIDkjCCAnqgAwIBAgIRAIW9S/PY2uNp9pTXX8OlRCMwDQYJKoZIhvcNAQEFBQAwPTELMAkGA1UE +BhMCRlIxETAPBgNVBAoTCENlcnRwbHVzMRswGQYDVQQDExJDbGFzcyAyIFByaW1hcnkgQ0EwHhcN +OTkwNzA3MTcwNTAwWhcNMTkwNzA2MjM1OTU5WjA9MQswCQYDVQQGEwJGUjERMA8GA1UEChMIQ2Vy +dHBsdXMxGzAZBgNVBAMTEkNsYXNzIDIgUHJpbWFyeSBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEP +ADCCAQoCggEBANxQltAS+DXSCHh6tlJw/W/uz7kRy1134ezpfgSN1sxvc0NXYKwzCkTsA18cgCSR +5aiRVhKC9+Ar9NuuYS6JEI1rbLqzAr3VNsVINyPi8Fo3UjMXEuLRYE2+L0ER4/YXJQyLkcAbmXuZ +Vg2v7tK8R1fjeUl7NIknJITesezpWE7+Tt9avkGtrAjFGA7v0lPubNCdEgETjdyAYveVqUSISnFO +YFWe2yMZeVYHDD9jC1yw4r5+FfyUM1hBOHTE4Y+L3yasH7WLO7dDWWuwJKZtkIvEcupdM5i3y95e +e++U8Rs+yskhwcWYAqqi9lt3m/V+llU0HGdpwPFC40es/CgcZlUCAwEAAaOBjDCBiTAPBgNVHRME +CDAGAQH/AgEKMAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQU43Mt38sOKAze3bOkynm4jrvoMIkwEQYJ +YIZIAYb4QgEBBAQDAgEGMDcGA1UdHwQwMC4wLKAqoCiGJmh0dHA6Ly93d3cuY2VydHBsdXMuY29t +L0NSTC9jbGFzczIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCnVM+IRBnL39R/AN9WM2K191EBkOvD +P9GIROkkXe/nFL0gt5o8AP5tn9uQ3Nf0YtaLcF3n5QRIqWh8yfFC82x/xXp8HVGIutIKPidd3i1R +TtMTZGnkLuPT55sJmabglZvOGtd/vjzOUrMRFcEPF80Du5wlFbqidon8BvEY0JNLDnyCt6X09l/+ +7UCmnYR0ObncHoUW2ikbhiMAybuJfm6AiB4vFLQDJKgybwOaRywwvlbGp0ICcBvqQNi6BQNwB6SW +//1IMwrh3KWBkJtN3X3n57LNXMhqlfil9o3EXXgIvnsG1knPGTZQIy4I5p4FTUcY1Rbpsda2ENW7 +l7+ijrRU +-----END CERTIFICATE----- + +DST Root CA X3 +============== +-----BEGIN CERTIFICATE----- +MIIDSjCCAjKgAwIBAgIQRK+wgNajJ7qJMDmGLvhAazANBgkqhkiG9w0BAQUFADA/MSQwIgYDVQQK +ExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMTDkRTVCBSb290IENBIFgzMB4X +DTAwMDkzMDIxMTIxOVoXDTIxMDkzMDE0MDExNVowPzEkMCIGA1UEChMbRGlnaXRhbCBTaWduYXR1 +cmUgVHJ1c3QgQ28uMRcwFQYDVQQDEw5EU1QgUm9vdCBDQSBYMzCCASIwDQYJKoZIhvcNAQEBBQAD +ggEPADCCAQoCggEBAN+v6ZdQCINXtMxiZfaQguzH0yxrMMpb7NnDfcdAwRgUi+DoM3ZJKuM/IUmT +rE4Orz5Iy2Xu/NMhD2XSKtkyj4zl93ewEnu1lcCJo6m67XMuegwGMoOifooUMM0RoOEqOLl5CjH9 +UL2AZd+3UWODyOKIYepLYYHsUmu5ouJLGiifSKOeDNoJjj4XLh7dIN9bxiqKqy69cK3FCxolkHRy +xXtqqzTWMIn/5WgTe1QLyNau7Fqckh49ZLOMxt+/yUFw7BZy1SbsOFU5Q9D8/RhcQPGX69Wam40d +utolucbY38EVAjqr2m7xPi71XAicPNaDaeQQmxkqtilX4+U9m5/wAl0CAwEAAaNCMEAwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMSnsaR7LHH62+FLkHX/xBVghYkQ +MA0GCSqGSIb3DQEBBQUAA4IBAQCjGiybFwBcqR7uKGY3Or+Dxz9LwwmglSBd49lZRNI+DT69ikug +dB/OEIKcdBodfpga3csTS7MgROSR6cz8faXbauX+5v3gTt23ADq1cEmv8uXrAvHRAosZy5Q6XkjE +GB5YGV8eAlrwDPGxrancWYaLbumR9YbK+rlmM6pZW87ipxZzR8srzJmwN0jP41ZL9c8PDHIyh8bw +RLtTcm1D9SZImlJnt1ir/md2cXjbDaJWFBM5JDGFoqgCWjBH4d1QB7wCCZAA62RjYJsWvIjJEubS +fZGL+T0yjWW06XyxV3bqxbYoOb8VZRzI9neWagqNdwvYkQsEjgfbKbYK7p2CNTUQ +-----END CERTIFICATE----- + +SwissSign Gold CA - G2 +====================== +-----BEGIN CERTIFICATE----- +MIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAkNIMRUw +EwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2lnbiBHb2xkIENBIC0gRzIwHhcN +MDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBFMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dp +c3NTaWduIEFHMR8wHQYDVQQDExZTd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUq +t2/876LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+bbqBHH5C +jCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c6bM8K8vzARO/Ws/BtQpg +vd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqEemA8atufK+ze3gE/bk3lUIbLtK/tREDF +ylqM2tIrfKjuvqblCqoOpd8FUrdVxyJdMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvR +AiTysybUa9oEVeXBCsdtMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuend +jIj3o02yMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69yFGkO +peUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPiaG59je883WX0XaxR +7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxMgI93e2CaHt+28kgeDrpOVG2Y4OGi +GqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUWyV7lqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64 +OfPAeGZe6Drn8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov +L3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe645R88a7A3hfm +5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczOUYrHUDFu4Up+GC9pWbY9ZIEr +44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5O1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOf +Mke6UiI0HTJ6CVanfCU2qT1L2sCCbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6m +Gu6uLftIdxf+u+yvGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxp +mo/a77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCChdiDyyJk +vC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid392qgQmwLOM7XdVAyksLf +KzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEppLd6leNcG2mqeSz53OiATIgHQv2ieY2Br +NU0LbbqhPcCT4H8js1WtciVORvnSFu+wZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6Lqj +viOvrv1vA+ACOzB2+httQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ +-----END CERTIFICATE----- + +SwissSign Silver CA - G2 +======================== +-----BEGIN CERTIFICATE----- +MIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCQ0gxFTAT +BgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMB4X +DTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0NlowRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3 +aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG +9w0BAQEFAAOCAg8AMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644 +N0MvFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7brYT7QbNHm ++/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieFnbAVlDLaYQ1HTWBCrpJH +6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH6ATK72oxh9TAtvmUcXtnZLi2kUpCe2Uu +MGoM9ZDulebyzYLs2aFK7PayS+VFheZteJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5h +qAaEuSh6XzjZG6k4sIN/c8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5 +FZGkECwJMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRHHTBs +ROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTfjNFusB3hB48IHpmc +celM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb65i/4z3GcRm25xBWNOHkDRUjvxF3X +CO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOBrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRB +tjpbO8tFnb0cwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0 +cDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBAHPGgeAn0i0P +4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShpWJHckRE1qTodvBqlYJ7YH39F +kWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9xCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L +3XWgwF15kIwb4FDm3jH+mHtwX6WQ2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx +/uNncqCxv1yL5PqZIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFa +DGi8aRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2Xem1ZqSqP +e97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQRdAtq/gsD/KNVV4n+Ssuu +WxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/OMpXEA29MC/HpeZBoNquBYeaoKRlbEwJ +DIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+hAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ub +DgEj8Z+7fNzcbBGXJbLytGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority +======================================== +-----BEGIN CERTIFICATE----- +MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQG +EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMoR2VvVHJ1c3QgUHJpbWFyeSBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjExMjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgx +CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQ +cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9AWbK7hWN +b6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjAZIVcFU2Ix7e64HXprQU9 +nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE07e9GceBrAqg1cmuXm2bgyxx5X9gaBGge +RwLmnWDiNpcB3841kt++Z8dtd1k7j53WkBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGt +tm/81w7a4DSwDRp35+MImO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJKoZI +hvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ16CePbJC/kRYkRj5K +Ts4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl4b7UVXGYNTq+k+qurUKykG/g/CFN +NWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6KoKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHa +Floxt/m0cYASSJlyc1pZU8FjUjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG +1riR/aYNKxoUAT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk= +-----END CERTIFICATE----- + +thawte Primary Root CA +====================== +-----BEGIN CERTIFICATE----- +MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UE +BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 +aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMTFnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwHhcNMDYxMTE3 +MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCBqTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwg +SW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMv +KGMpIDIwMDYgdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxHzAdBgNVBAMT +FnRoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCs +oPD7gFnUnMekz52hWXMJEEUMDSxuaPFsW0hoSVk3/AszGcJ3f8wQLZU0HObrTQmnHNK4yZc2AreJ +1CRfBsDMRJSUjQJib+ta3RGNKJpchJAQeg29dGYvajig4tVUROsdB58Hum/u6f1OCyn1PoSgAfGc +q/gcfomk6KHYcWUNo1F77rzSImANuVud37r8UVsLr5iy6S7pBOhih94ryNdOwUxkHt3Ph1i6Sk/K +aAcdHJ1KxtUvkcx8cXIcxcBn6zL9yZJclNqFwJu/U30rCfSMnZEfl2pSy94JNqR32HuHUETVPm4p +afs5SSYeCaWAe0At6+gnhcn+Yf1+5nyXHdWdAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR7W0XPr87Lev0xkhpqtvNG61dIUDANBgkqhkiG9w0BAQUF +AAOCAQEAeRHAS7ORtvzw6WfUDW5FvlXok9LOAz/t2iWwHVfLHjp2oEzsUHboZHIMpKnxuIvW1oeE +uzLlQRHAd9mzYJ3rG9XRbkREqaYB7FViHXe4XI5ISXycO1cRrK1zN44veFyQaEfZYGDm/Ac9IiAX +xPcW6cTYcvnIc3zfFi8VqT79aie2oetaupgf1eNNZAqdE8hhuvU5HIe6uL17In/2/qxAeeWsEG89 +jxt5dovEN7MhGITlNgDrYyCZuen+MwS7QcjBAvlEYyCegc5C09Y/LHbTY5xZ3Y+m4Q6gLkH3LpVH +z7z9M/P2C2F+fpErgUfCJzDupxBdN49cOSvkBPB7jVaMaA== +-----END CERTIFICATE----- + +VeriSign Class 3 Public Primary Certification Authority - G5 +============================================================ +-----BEGIN CERTIFICATE----- +MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE +BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO +ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk +IHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRp +ZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCB +yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln +biBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBh +dXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmlt +YXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCvJAgIKXo1nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKz +j/i5Vbext0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIzSdhD +Y2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQGBO+QueQA5N06tRn/ +Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+rCpSx4/VBEnkjWNHiDxpg8v+R70r +fk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/ +BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2Uv +Z2lmMCEwHzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy +aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKvMzEzMA0GCSqG +SIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzEp6B4Eq1iDkVwZMXnl2YtmAl+ +X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKE +KQsTb47bDN0lAtukixlE0kF6BWlKWE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiC +Km0oHw0LxOXnGiYZ4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vE +ZV8NhnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq +-----END CERTIFICATE----- + +SecureTrust CA +============== +-----BEGIN CERTIFICATE----- +MIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBIMQswCQYDVQQG +EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xFzAVBgNVBAMTDlNlY3VyZVRy +dXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIzMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAe +BgNVBAoTF1NlY3VyZVRydXN0IENvcnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCC +ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQX +OZEzZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO0gMdA+9t +DWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIaowW8xQmxSPmjL8xk037uH +GFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b +01k/unK8RCSc43Oz969XL0Imnal0ugBS8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmH +ursCAwEAAaOBnTCBmjATBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/ +BAUwAwEB/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCegJYYj +aHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ +KoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt36Z3q059c4EVlew3KW+JwULKUBRSu +SceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHf +mbx8IVQr5Fiiu1cprp6poxkmD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZ +nMUFdAvnZyPSCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR +3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE= +-----END CERTIFICATE----- + +Secure Global CA +================ +-----BEGIN CERTIFICATE----- +MIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQG +EwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBH +bG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkxMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEg +MB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwg +Q0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jx +YDiJiQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa/FHtaMbQ +bqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJjnIFHovdRIWCQtBJwB1g +8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnIHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYV +HDGA76oYa8J719rO+TMg1fW9ajMtgQT7sFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi +0XPnj3pDAgMBAAGjgZ0wgZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1Ud +EwEB/wQFMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCswKaAn +oCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsGAQQBgjcVAQQDAgEA +MA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0LURYD7xh8yOOvaliTFGCRsoTciE6+ +OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXOH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cn +CDpOGR86p1hcF895P4vkp9MmI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/5 +3CYNv6ZHdAbYiNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc +f8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW +-----END CERTIFICATE----- + +COMODO Certification Authority +============================== +-----BEGIN CERTIFICATE----- +MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCBgTELMAkGA1UE +BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG +A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNVBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1 +dGhvcml0eTAeFw0wNjEyMDEwMDAwMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEb +MBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFD +T01PRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3UcEbVASY06m/weaKXTuH ++7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI2GqGd0S7WWaXUF601CxwRM/aN5VCaTww +xHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV +4EajcNxo2f8ESIl33rXp+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA +1KGzqSX+DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5OnKVI +rLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9k +b2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOC +AQEAPpiem/Yb6dc5t3iuHXIYSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CP +OGEIqB6BCsAvIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ +RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4zJVSk/BwJVmc +IGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5ddBA6+C4OmF4O5MBKgxTMVBbkN ++8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IBZQ== +-----END CERTIFICATE----- + +Network Solutions Certificate Authority +======================================= +-----BEGIN CERTIFICATE----- +MIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBiMQswCQYDVQQG +EwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydOZXR3b3Jr +IFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMx +MjM1OTU5WjBiMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu +MTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0G +CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwzc7MEL7xx +jOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPPOCwGJgl6cvf6UDL4wpPT +aaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rlmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXT +crA/vGp97Eh/jcOrqnErU2lBUzS1sLnFBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc +/Qzpf14Dl847ABSHJ3A4qY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMB +AAGjgZcwgZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwubmV0c29sc3NsLmNv +bS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3JpdHkuY3JsMA0GCSqGSIb3DQEBBQUA +A4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc86fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q +4LqILPxFzBiwmZVRDuwduIj/h1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/ +GGUsyfJj4akH/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv +wKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHNpGxlaKFJdlxD +ydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey +-----END CERTIFICATE----- + +COMODO ECC Certification Authority +================================== +-----BEGIN CERTIFICATE----- +MIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTELMAkGA1UEBhMC +R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE +ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwHhcNMDgwMzA2MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0Ix +GzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR +Q09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRo +b3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSRFtSrYpn1PlILBs5BAH+X +4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0JcfRK9ChQtP6IHG4/bC8vCVlbpVsLM5ni +wz2J+Wos77LTBumjQjBAMB0GA1UdDgQWBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8E +BAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VG +FAkK+qDmfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdvGDeA +U/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY= +-----END CERTIFICATE----- + +OISTE WISeKey Global Root GA CA +=============================== +-----BEGIN CERTIFICATE----- +MIID8TCCAtmgAwIBAgIQQT1yx/RrH4FDffHSKFTfmjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE +BhMCQ0gxEDAOBgNVBAoTB1dJU2VLZXkxGzAZBgNVBAsTEkNvcHlyaWdodCAoYykgMjAwNTEiMCAG +A1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBH +bG9iYWwgUm9vdCBHQSBDQTAeFw0wNTEyMTExNjAzNDRaFw0zNzEyMTExNjA5NTFaMIGKMQswCQYD +VQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEbMBkGA1UECxMSQ29weXJpZ2h0IChjKSAyMDA1MSIw +IAYDVQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5 +IEdsb2JhbCBSb290IEdBIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy0+zAJs9 +Nt350UlqaxBJH+zYK7LG+DKBKUOVTJoZIyEVRd7jyBxRVVuuk+g3/ytr6dTqvirdqFEr12bDYVxg +Asj1znJ7O7jyTmUIms2kahnBAbtzptf2w93NvKSLtZlhuAGio9RN1AU9ka34tAhxZK9w8RxrfvbD +d50kc3vkDIzh2TbhmYsFmQvtRTEJysIA2/dyoJaqlYfQjse2YXMNdmaM3Bu0Y6Kff5MTMPGhJ9vZ +/yxViJGg4E8HsChWjBgbl0SOid3gF27nKu+POQoxhILYQBRJLnpB5Kf+42TMwVlxSywhp1t94B3R +LoGbw9ho972WG6xwsRYUC9tguSYBBQIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw +AwEB/zAdBgNVHQ4EFgQUswN+rja8sHnR3JQmthG+IbJphpQwEAYJKwYBBAGCNxUBBAMCAQAwDQYJ +KoZIhvcNAQEFBQADggEBAEuh/wuHbrP5wUOxSPMowB0uyQlB+pQAHKSkq0lPjz0e701vvbyk9vIm +MMkQyh2I+3QZH4VFvbBsUfk2ftv1TDI6QU9bR8/oCy22xBmddMVHxjtqD6wU2zz0c5ypBd8A3HR4 ++vg1YFkCExh8vPtNsCBtQ7tgMHpnM1zFmdH4LTlSc/uMqpclXHLZCB6rTjzjgTGfA6b7wP4piFXa +hNVQA7bihKOmNqoROgHhGEvWRGizPflTdISzRpFGlgC3gCy24eMQ4tui5yiPAZZiFj4A4xylNoEY +okxSdsARo27mHbrjWr42U8U+dY+GaSlYU7Wcu2+fXMUY7N0v4ZjJ/L7fCg0= +-----END CERTIFICATE----- + +Certigna +======== +-----BEGIN CERTIFICATE----- +MIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNVBAYTAkZSMRIw +EAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4XDTA3MDYyOTE1MTMwNVoXDTI3 +MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwI +Q2VydGlnbmEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7q +XOEm7RFHYeGifBZ4QCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyH +GxnygQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbwzBfsV1/p +ogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q130yGLMLLGq/jj8UEYkg +DncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2JsglrgVKtOdjLPOMFlN+XPsRGgjBRmKf +Irjxwo1p3Po6WAbfAgMBAAGjgbwwgbkwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQ +tCRZvgHyUtVF9lo53BEwZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJ +BgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzjAQ/J +SP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG9w0BAQUFAAOCAQEA +hQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8hbV6lUmPOEvjvKtpv6zf+EwLHyzs+ +ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFncfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1klu +PBS1xp81HlDQwY9qcEQCYsuuHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY +1gkIl2PlwS6wt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw +WyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg== +-----END CERTIFICATE----- + +Deutsche Telekom Root CA 2 +========================== +-----BEGIN CERTIFICATE----- +MIIDnzCCAoegAwIBAgIBJjANBgkqhkiG9w0BAQUFADBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMT +RGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0GA1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEG +A1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBSb290IENBIDIwHhcNOTkwNzA5MTIxMTAwWhcNMTkwNzA5 +MjM1OTAwWjBxMQswCQYDVQQGEwJERTEcMBoGA1UEChMTRGV1dHNjaGUgVGVsZWtvbSBBRzEfMB0G +A1UECxMWVC1UZWxlU2VjIFRydXN0IENlbnRlcjEjMCEGA1UEAxMaRGV1dHNjaGUgVGVsZWtvbSBS +b290IENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrC6M14IspFLEUha88EOQ5 +bzVdSq7d6mGNlUn0b2SjGmBmpKlAIoTZ1KXleJMOaAGtuU1cOs7TuKhCQN/Po7qCWWqSG6wcmtoI +KyUn+WkjR/Hg6yx6m/UTAtB+NHzCnjwAWav12gz1MjwrrFDa1sPeg5TKqAyZMg4ISFZbavva4VhY +AUlfckE8FQYBjl2tqriTtM2e66foai1SNNs671x1Udrb8zH57nGYMsRUFUQM+ZtV7a3fGAigo4aK +Se5TBY8ZTNXeWHmb0mocQqvF1afPaA+W5OFhmHZhyJF81j4A4pFQh+GdCuatl9Idxjp9y7zaAzTV +jlsB9WoHtxa2bkp/AgMBAAGjQjBAMB0GA1UdDgQWBBQxw3kbuvVT1xfgiXotF2wKsyudMzAPBgNV +HRMECDAGAQH/AgEFMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQUFAAOCAQEAlGRZrTlk5ynr +E/5aw4sTV8gEJPB0d8Bg42f76Ymmg7+Wgnxu1MM9756AbrsptJh6sTtU6zkXR34ajgv8HzFZMQSy +zhfzLMdiNlXiItiJVbSYSKpk+tYcNthEeFpaIzpXl/V6ME+un2pMSyuOoAPjPuCp1NJ70rOo4nI8 +rZ7/gFnkm0W09juwzTkZmDLl6iFhkOQxIY40sfcvNUqFENrnijchvllj4PKFiDFT1FQUhXB59C4G +dyd1Lx+4ivn+xbrYNuSD7Odlt79jWvNGr4GUN9RBjNYj1h7P9WgbRGOiWrqnNVmh5XAFmw4jV5mU +Cm26OWMohpLzGITY+9HPBVZkVw== +-----END CERTIFICATE----- + +Cybertrust Global Root +====================== +-----BEGIN CERTIFICATE----- +MIIDoTCCAomgAwIBAgILBAAAAAABD4WqLUgwDQYJKoZIhvcNAQEFBQAwOzEYMBYGA1UEChMPQ3li +ZXJ0cnVzdCwgSW5jMR8wHQYDVQQDExZDeWJlcnRydXN0IEdsb2JhbCBSb290MB4XDTA2MTIxNTA4 +MDAwMFoXDTIxMTIxNTA4MDAwMFowOzEYMBYGA1UEChMPQ3liZXJ0cnVzdCwgSW5jMR8wHQYDVQQD +ExZDeWJlcnRydXN0IEdsb2JhbCBSb290MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA ++Mi8vRRQZhP/8NN57CPytxrHjoXxEnOmGaoQ25yiZXRadz5RfVb23CO21O1fWLE3TdVJDm71aofW +0ozSJ8bi/zafmGWgE07GKmSb1ZASzxQG9Dvj1Ci+6A74q05IlG2OlTEQXO2iLb3VOm2yHLtgwEZL +AfVJrn5GitB0jaEMAs7u/OePuGtm839EAL9mJRQr3RAwHQeWP032a7iPt3sMpTjr3kfb1V05/Iin +89cqdPHoWqI7n1C6poxFNcJQZZXcY4Lv3b93TZxiyWNzFtApD0mpSPCzqrdsxacwOUBdrsTiXSZT +8M4cIwhhqJQZugRiQOwfOHB3EgZxpzAYXSUnpQIDAQABo4GlMIGiMA4GA1UdDwEB/wQEAwIBBjAP +BgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBS2CHsNesysIEyGVjJez6tuhS1wVzA/BgNVHR8EODA2 +MDSgMqAwhi5odHRwOi8vd3d3Mi5wdWJsaWMtdHJ1c3QuY29tL2NybC9jdC9jdHJvb3QuY3JsMB8G +A1UdIwQYMBaAFLYIew16zKwgTIZWMl7Pq26FLXBXMA0GCSqGSIb3DQEBBQUAA4IBAQBW7wojoFRO +lZfJ+InaRcHUowAl9B8Tq7ejhVhpwjCt2BWKLePJzYFa+HMjWqd8BfP9IjsO0QbE2zZMcwSO5bAi +5MXzLqXZI+O4Tkogp24CJJ8iYGd7ix1yCcUxXOl5n4BHPa2hCwcUPUf/A2kaDAtE52Mlp3+yybh2 +hO0j9n0Hq0V+09+zv+mKts2oomcrUtW3ZfA5TGOgkXmTUg9U3YO7n9GPp1Nzw8v/MOx8BLjYRB+T +X3EJIrduPuocA06dGiBh+4E37F78CkWr1+cXVdCg6mCbpvbjjFspwgZgFJ0tl0ypkxWdYcQBX0jW +WL1WMRJOEcgh4LMRkWXbtKaIOM5V +-----END CERTIFICATE----- + +ePKI Root Certification Authority +================================= +-----BEGIN CERTIFICATE----- +MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBeMQswCQYDVQQG +EwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0ZC4xKjAoBgNVBAsMIWVQS0kg +Um9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMx +MjdaMF4xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEq +MCgGA1UECwwhZVBLSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAHSyZbCUNs +IZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAhijHyl3SJCRImHJ7K2RKi +lTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3XDZoTM1PRYfl61dd4s5oz9wCGzh1NlDiv +qOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX +12ruOzjjK9SXDrkb5wdJfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0O +WQqraffAsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uUWH1+ +ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLSnT0IFaUQAS2zMnao +lQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pHdmX2Os+PYhcZewoozRrSgx4hxyy/ +vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJipNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXi +Zo1jDiVN1Rmy5nk3pyKdVDECAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/Qkqi +MAwGA1UdEwQFMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH +ClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGBuvl2ICO1J2B0 +1GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6YlPwZpVnPDimZI+ymBV3QGypzq +KOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkPJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdV +xrsStZf0X4OFunHB2WyBEXYKCrC/gpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEP +NXubrjlpC2JgQCA2j6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+r +GNm65ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUBo2M3IUxE +xJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS/jQ6fbjpKdx2qcgw+BRx +gMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2zGp1iro2C6pSe3VkQw63d4k3jMdXH7Ojy +sP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTEW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmOD +BCEIZ43ygknQW/2xzQ+DhNQ+IIX3Sj0rnP0qCglN6oH4EZw= +-----END CERTIFICATE----- + +certSIGN ROOT CA +================ +-----BEGIN CERTIFICATE----- +MIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYTAlJPMREwDwYD +VQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTAeFw0wNjA3MDQxNzIwMDRa +Fw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UE +CxMQY2VydFNJR04gUk9PVCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7I +JUqOtdu0KBuqV5Do0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHH +rfAQUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5dRdY4zTW2 +ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQOA7+j0xbm0bqQfWwCHTD +0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwvJoIQ4uNllAoEwF73XVv4EOLQunpL+943 +AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B +Af8EBAMCAcYwHQYDVR0OBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IB +AQA+0hyJLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecYMnQ8 +SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ44gx+FkagQnIl6Z0 +x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6IJd1hJyMctTEHBDa0GpC9oHRxUIlt +vBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNwi/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7Nz +TogVZ96edhBiIL5VaZVDADlN9u6wWk5JRFRYX0KD +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority - G3 +============================================= +-----BEGIN CERTIFICATE----- +MIID/jCCAuagAwIBAgIQFaxulBmyeUtB9iepwxgPHzANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UE +BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA4IEdlb1RydXN0 +IEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFy +eSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEczMB4XDTA4MDQwMjAwMDAwMFoXDTM3MTIwMTIz +NTk1OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAo +YykgMjAwOCBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMT +LUdlb1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMzCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBANziXmJYHTNXOTIz+uvLh4yn1ErdBojqZI4xmKU4kB6Yzy5j +K/BGvESyiaHAKAxJcCGVn2TAppMSAmUmhsalifD614SgcK9PGpc/BkTVyetyEH3kMSj7HGHmKAdE +c5IiaacDiGydY8hS2pgn5whMcD60yRLBxWeDXTPzAxHsatBT4tG6NmCUgLthY2xbF37fQJQeqw3C +IShwiP/WJmxsYAQlTlV+fe+/lEjetx3dcI0FX4ilm/LC7urRQEFtYjgdVgbFA0dRIBn8exALDmKu +dlW/X3e+PkkBUz2YJQN2JFodtNuJ6nnltrM7P7pMKEF/BqxqjsHQ9gUdfeZChuOl1UcCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFMR5yo6hTgMdHNxr +2zFblD4/MH8tMA0GCSqGSIb3DQEBCwUAA4IBAQAtxRPPVoB7eni9n64smefv2t+UXglpp+duaIy9 +cr5HqQ6XErhK8WTTOd8lNNTBzU6B8A8ExCSzNJbGpqow32hhc9f5joWJ7w5elShKKiePEI4ufIbE +Ap7aDHdlDkQNkv39sxY2+hENHYwOB4lqKVb3cvTdFZx3NWZXqxNT2I7BQMXXExZacse3aQHEerGD +AWh9jUGhlBjBJVz88P6DAod8DQ3PLghcSkANPuyBYeYk28rgDi0Hsj5W3I31QYUHSJsMC8tJP33s +t/3LjWeJGqvtux6jAAgIFyqCXDFdRootD4abdNlF+9RAsXqqaC2Gspki4cErx5z481+oghLrGREt +-----END CERTIFICATE----- + +thawte Primary Root CA - G2 +=========================== +-----BEGIN CERTIFICATE----- +MIICiDCCAg2gAwIBAgIQNfwmXNmET8k9Jj1Xm67XVjAKBggqhkjOPQQDAzCBhDELMAkGA1UEBhMC +VVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjE4MDYGA1UECxMvKGMpIDIwMDcgdGhhd3RlLCBJbmMu +IC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3Qg +Q0EgLSBHMjAeFw0wNzExMDUwMDAwMDBaFw0zODAxMTgyMzU5NTlaMIGEMQswCQYDVQQGEwJVUzEV +MBMGA1UEChMMdGhhd3RlLCBJbmMuMTgwNgYDVQQLEy8oYykgMjAwNyB0aGF3dGUsIEluYy4gLSBG +b3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIGA1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAt +IEcyMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEotWcgnuVnfFSeIf+iha/BebfowJPDQfGAFG6DAJS +LSKkQjnE/o/qycG+1E3/n3qe4rF8mq2nhglzh9HnmuN6papu+7qzcMBniKI11KOasf2twu8x+qi5 +8/sIxpHR+ymVo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU +mtgAMADna3+FGO6Lts6KDPgR4bswCgYIKoZIzj0EAwMDaQAwZgIxAN344FdHW6fmCsO99YCKlzUN +G4k8VIZ3KMqh9HneteY4sPBlcIx/AlTCv//YoT7ZzwIxAMSNlPzcU9LcnXgWHxUzI1NS41oxXZ3K +rr0TKUQNJ1uo52icEvdYPy5yAlejj6EULg== +-----END CERTIFICATE----- + +thawte Primary Root CA - G3 +=========================== +-----BEGIN CERTIFICATE----- +MIIEKjCCAxKgAwIBAgIQYAGXt0an6rS0mtZLL/eQ+zANBgkqhkiG9w0BAQsFADCBrjELMAkGA1UE +BhMCVVMxFTATBgNVBAoTDHRoYXd0ZSwgSW5jLjEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2 +aWNlcyBEaXZpc2lvbjE4MDYGA1UECxMvKGMpIDIwMDggdGhhd3RlLCBJbmMuIC0gRm9yIGF1dGhv +cml6ZWQgdXNlIG9ubHkxJDAiBgNVBAMTG3RoYXd0ZSBQcmltYXJ5IFJvb3QgQ0EgLSBHMzAeFw0w +ODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIGuMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMdGhh +d3RlLCBJbmMuMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMTgwNgYD +VQQLEy8oYykgMjAwOCB0aGF3dGUsIEluYy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTEkMCIG +A1UEAxMbdGhhd3RlIFByaW1hcnkgUm9vdCBDQSAtIEczMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAsr8nLPvb2FvdeHsbnndmgcs+vHyu86YnmjSjaDFxODNi5PNxZnmxqWWjpYvVj2At +P0LMqmsywCPLLEHd5N/8YZzic7IilRFDGF/Eth9XbAoFWCLINkw6fKXRz4aviKdEAhN0cXMKQlkC ++BsUa0Lfb1+6a4KinVvnSr0eAXLbS3ToO39/fR8EtCab4LRarEc9VbjXsCZSKAExQGbY2SS99irY +7CFJXJv2eul/VTV+lmuNk5Mny5K76qxAwJ/C+IDPXfRa3M50hqY+bAtTyr2SzhkGcuYMXDhpxwTW +vGzOW/b3aJzcJRVIiKHpqfiYnODz1TEoYRFsZ5aNOZnLwkUkOQIDAQABo0IwQDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUrWyqlGCc7eT/+j4KdCtjA/e2Wb8wDQYJ +KoZIhvcNAQELBQADggEBABpA2JVlrAmSicY59BDlqQ5mU1143vokkbvnRFHfxhY0Cu9qRFHqKweK +A3rD6z8KLFIWoCtDuSWQP3CpMyVtRRooOyfPqsMpQhvfO0zAMzRbQYi/aytlryjvsvXDqmbOe1bu +t8jLZ8HJnBoYuMTDSQPxYA5QzUbF83d597YV4Djbxy8ooAw/dyZ02SUS2jHaGh7cKUGRIjxpp7sC +8rZcJwOJ9Abqm+RyguOhCcHpABnTPtRwa7pxpqpYrvS76Wy274fMm7v/OeZWYdMKp8RcTGB7BXcm +er/YB1IsYvdwY9k5vG8cwnncdimvzsUsZAReiDZuMdRAGmI0Nj81Aa6sY6A= +-----END CERTIFICATE----- + +GeoTrust Primary Certification Authority - G2 +============================================= +-----BEGIN CERTIFICATE----- +MIICrjCCAjWgAwIBAgIQPLL0SAoA4v7rJDteYD7DazAKBggqhkjOPQQDAzCBmDELMAkGA1UEBhMC +VVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xOTA3BgNVBAsTMChjKSAyMDA3IEdlb1RydXN0IElu +Yy4gLSBGb3IgYXV0aG9yaXplZCB1c2Ugb25seTE2MDQGA1UEAxMtR2VvVHJ1c3QgUHJpbWFyeSBD +ZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEcyMB4XDTA3MTEwNTAwMDAwMFoXDTM4MDExODIzNTk1 +OVowgZgxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMTkwNwYDVQQLEzAoYykg +MjAwNyBHZW9UcnVzdCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxNjA0BgNVBAMTLUdl +b1RydXN0IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgLSBHMjB2MBAGByqGSM49AgEG +BSuBBAAiA2IABBWx6P0DFUPlrOuHNxFi79KDNlJ9RVcLSo17VDs6bl8VAsBQps8lL33KSLjHUGMc +KiEIfJo22Av+0SbFWDEwKCXzXV2juLaltJLtbCyf691DiaI8S0iRHVDsJt/WYC69IaNCMEAwDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBVfNVdRVfslsq0DafwBo/q+ +EVXVMAoGCCqGSM49BAMDA2cAMGQCMGSWWaboCd6LuvpaiIjwH5HTRqjySkwCY/tsXzjbLkGTqQ7m +ndwxHLKgpxgceeHHNgIwOlavmnRs9vuD4DPTCF+hnMJbn0bWtsuRBmOiBuczrD6ogRLQy7rQkgu2 +npaqBA+K +-----END CERTIFICATE----- + +VeriSign Universal Root Certification Authority +=============================================== +-----BEGIN CERTIFICATE----- +MIIEuTCCA6GgAwIBAgIQQBrEZCGzEyEDDrvkEhrFHTANBgkqhkiG9w0BAQsFADCBvTELMAkGA1UE +BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO +ZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwOCBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVk +IHVzZSBvbmx5MTgwNgYDVQQDEy9WZXJpU2lnbiBVbml2ZXJzYWwgUm9vdCBDZXJ0aWZpY2F0aW9u +IEF1dGhvcml0eTAeFw0wODA0MDIwMDAwMDBaFw0zNzEyMDEyMzU5NTlaMIG9MQswCQYDVQQGEwJV +UzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRydXN0IE5ldHdv +cmsxOjA4BgNVBAsTMShjKSAyMDA4IFZlcmlTaWduLCBJbmMuIC0gRm9yIGF1dGhvcml6ZWQgdXNl +IG9ubHkxODA2BgNVBAMTL1ZlcmlTaWduIFVuaXZlcnNhbCBSb290IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx2E3XrEBNNti1xWb/1hajCMj +1mCOkdeQmIN65lgZOIzF9uVkhbSicfvtvbnazU0AtMgtc6XHaXGVHzk8skQHnOgO+k1KxCHfKWGP +MiJhgsWHH26MfF8WIFFE0XBPV+rjHOPMee5Y2A7Cs0WTwCznmhcrewA3ekEzeOEz4vMQGn+HLL72 +9fdC4uW/h2KJXwBL38Xd5HVEMkE6HnFuacsLdUYI0crSK5XQz/u5QGtkjFdN/BMReYTtXlT2NJ8I +AfMQJQYXStrxHXpma5hgZqTZ79IugvHw7wnqRMkVauIDbjPTrJ9VAMf2CGqUuV/c4DPxhGD5WycR +tPwW8rtWaoAljQIDAQABo4GyMIGvMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMG0G +CCsGAQUFBwEMBGEwX6FdoFswWTBXMFUWCWltYWdlL2dpZjAhMB8wBwYFKw4DAhoEFI/l0xqGrI2O +a8PPgGrUSBgsexkuMCUWI2h0dHA6Ly9sb2dvLnZlcmlzaWduLmNvbS92c2xvZ28uZ2lmMB0GA1Ud +DgQWBBS2d/ppSEefUxLVwuoHMnYH0ZcHGTANBgkqhkiG9w0BAQsFAAOCAQEASvj4sAPmLGd75JR3 +Y8xuTPl9Dg3cyLk1uXBPY/ok+myDjEedO2Pzmvl2MpWRsXe8rJq+seQxIcaBlVZaDrHC1LGmWazx +Y8u4TB1ZkErvkBYoH1quEPuBUDgMbMzxPcP1Y+Oz4yHJJDnp/RVmRvQbEdBNc6N9Rvk97ahfYtTx +P/jgdFcrGJ2BtMQo2pSXpXDrrB2+BxHw1dvd5Yzw1TKwg+ZX4o+/vqGqvz0dtdQ46tewXDpPaj+P +wGZsY6rp2aQW9IHRlRQOfc2VNNnSj3BzgXucfr2YYdhFh5iQxeuGMMY1v/D/w1WIg0vvBZIGcfK4 +mJO37M2CYfE45k+XmCpajQ== +-----END CERTIFICATE----- + +VeriSign Class 3 Public Primary Certification Authority - G4 +============================================================ +-----BEGIN CERTIFICATE----- +MIIDhDCCAwqgAwIBAgIQL4D+I4wOIg9IZxIokYesszAKBggqhkjOPQQDAzCByjELMAkGA1UEBhMC +VVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3 +b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVz +ZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmlj +YXRpb24gQXV0aG9yaXR5IC0gRzQwHhcNMDcxMTA1MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBU +cnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNyBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRo +b3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5 +IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzQwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASnVnp8 +Utpkmw4tXNherJI9/gHmGUo9FANL+mAnINmDiWn6VMaaGF5VKmTeBvaNSjutEDxlPZCIBIngMGGz +rl0Bp3vefLK+ymVhAIau2o970ImtTR1ZmkGxvEeA3J5iw/mjgbIwga8wDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEw +HzAHBgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVyaXNpZ24u +Y29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFLMWkf3upm7ktS5Jj4d4gYDs5bG1MAoGCCqGSM49BAMD +A2gAMGUCMGYhDBgmYFo4e1ZC4Kf8NoRRkSAsdk1DPcQdhCPQrNZ8NQbOzWm9kA3bbEhCHQ6qQgIx +AJw9SDkjOVgaFRJZap7v1VmyHVIsmXHNxynfGyphe3HR3vPA5Q06Sqotp9iGKt0uEA== +-----END CERTIFICATE----- + +NetLock Arany (Class Gold) Főtanúsítvány +======================================== +-----BEGIN CERTIFICATE----- +MIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQGEwJIVTERMA8G +A1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3MDUGA1UECwwuVGFuw7pzw610 +dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBB +cmFueSAoQ2xhc3MgR29sZCkgRsWRdGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgx +MjA2MTUwODIxWjCBpzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxO +ZXRMb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlmaWNhdGlv +biBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNzIEdvbGQpIEbFkXRhbsO6 +c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu +0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrTlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw +/HpYzY6b7cNGbIRwXdrzAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAk +H3B5r9s5VA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRGILdw +fzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2BJtr+UBdADTHLpl1 +neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAGAQH/AgEEMA4GA1UdDwEB/wQEAwIB +BjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2MU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwW +qZw8UQCgwBEIBaeZ5m8BiFRhbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTta +YtOUZcTh5m2C+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC +bLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2FuLjbvrW5Kfna +NwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2XjG4Kvte9nHfRCaexOYNkbQu +dZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E= +-----END CERTIFICATE----- + +Staat der Nederlanden Root CA - G2 +================================== +-----BEGIN CERTIFICATE----- +MIIFyjCCA7KgAwIBAgIEAJiWjDANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE +CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g +Um9vdCBDQSAtIEcyMB4XDTA4MDMyNjExMTgxN1oXDTIwMDMyNTExMDMxMFowWjELMAkGA1UEBhMC +TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l +ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMVZ +5291qj5LnLW4rJ4L5PnZyqtdj7U5EILXr1HgO+EASGrP2uEGQxGZqhQlEq0i6ABtQ8SpuOUfiUtn +vWFI7/3S4GCI5bkYYCjDdyutsDeqN95kWSpGV+RLufg3fNU254DBtvPUZ5uW6M7XxgpT0GtJlvOj +CwV3SPcl5XCsMBQgJeN/dVrlSPhOewMHBPqCYYdu8DvEpMfQ9XQ+pV0aCPKbJdL2rAQmPlU6Yiil +e7Iwr/g3wtG61jj99O9JMDeZJiFIhQGp5Rbn3JBV3w/oOM2ZNyFPXfUib2rFEhZgF1XyZWampzCR +OME4HYYEhLoaJXhena/MUGDWE4dS7WMfbWV9whUYdMrhfmQpjHLYFhN9C0lK8SgbIHRrxT3dsKpI +CT0ugpTNGmXZK4iambwYfp/ufWZ8Pr2UuIHOzZgweMFvZ9C+X+Bo7d7iscksWXiSqt8rYGPy5V65 +48r6f1CGPqI0GAwJaCgRHOThuVw+R7oyPxjMW4T182t0xHJ04eOLoEq9jWYv6q012iDTiIJh8BIi +trzQ1aTsr1SIJSQ8p22xcik/Plemf1WvbibG/ufMQFxRRIEKeN5KzlW/HdXZt1bv8Hb/C3m1r737 +qWmRRpdogBQ2HbN/uymYNqUg+oJgYjOk7Na6B6duxc8UpufWkjTYgfX8HV2qXB72o007uPc5AgMB +AAGjgZcwgZQwDwYDVR0TAQH/BAUwAwEB/zBSBgNVHSAESzBJMEcGBFUdIAAwPzA9BggrBgEFBQcC +ARYxaHR0cDovL3d3dy5wa2lvdmVyaGVpZC5ubC9wb2xpY2llcy9yb290LXBvbGljeS1HMjAOBgNV +HQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJFoMocVHYnitfGsNig0jQt8YojrMA0GCSqGSIb3DQEBCwUA +A4ICAQCoQUpnKpKBglBu4dfYszk78wIVCVBR7y29JHuIhjv5tLySCZa59sCrI2AGeYwRTlHSeYAz ++51IvuxBQ4EffkdAHOV6CMqqi3WtFMTC6GY8ggen5ieCWxjmD27ZUD6KQhgpxrRW/FYQoAUXvQwj +f/ST7ZwaUb7dRUG/kSS0H4zpX897IZmflZ85OkYcbPnNe5yQzSipx6lVu6xiNGI1E0sUOlWDuYaN +kqbG9AclVMwWVxJKgnjIFNkXgiYtXSAfea7+1HAWFpWD2DU5/1JddRwWxRNVz0fMdWVSSt7wsKfk +CpYL+63C4iWEst3kvX5ZbJvw8NjnyvLplzh+ib7M+zkXYT9y2zqR2GUBGR2tUKRXCnxLvJxxcypF +URmFzI79R6d0lR2o0a9OF7FpJsKqeFdbxU2n5Z4FF5TKsl+gSRiNNOkmbEgeqmiSBeGCc1qb3Adb +CG19ndeNIdn8FCCqwkXfP+cAslHkwvgFuXkajDTznlvkN1trSt8sV4pAWja63XVECDdCcAz+3F4h +oKOKwJCcaNpQ5kUQR3i2TtJlycM33+FCY7BXN0Ute4qcvwXqZVUz9zkQxSgqIXobisQk+T8VyJoV +IPVVYpbtbZNQvOSqeK3Zywplh6ZmwcSBo3c6WB4L7oOLnR7SUqTMHW+wmG2UMbX4cQrcufx9MmDm +66+KAQ== +-----END CERTIFICATE----- + +Hongkong Post Root CA 1 +======================= +-----BEGIN CERTIFICATE----- +MIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoT +DUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMB4XDTAzMDUx +NTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkGA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25n +IFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1 +ApzQjVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEnPzlTCeqr +auh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjhZY4bXSNmO7ilMlHIhqqh +qZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9nnV0ttgCXjqQesBCNnLsak3c78QA3xMY +V18meMjWCnl3v/evt3a5pQuEF10Q6m/hq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNV +HRMBAf8ECDAGAQH/AgEDMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7i +h9legYsCmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI37pio +l7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clBoiMBdDhViw+5Lmei +IAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJsEhTkYY2sEJCehFC78JZvRZ+K88ps +T/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpOfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilT +c4afU9hDDl3WY4JxHYB0yvbiAmvZWg== +-----END CERTIFICATE----- + +SecureSign RootCA11 +=================== +-----BEGIN CERTIFICATE----- +MIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDErMCkGA1UEChMi +SmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoGA1UEAxMTU2VjdXJlU2lnbiBS +b290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0MDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSsw +KQYDVQQKEyJKYXBhbiBDZXJ0aWZpY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1 +cmVTaWduIFJvb3RDQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvL +TJszi1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8h9uuywGO +wvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOVMdrAG/LuYpmGYz+/3ZMq +g6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9UK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rP +O7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitA +bpSACW22s293bzUIUPsCh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZX +t94wDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEBAKCh +OBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xmKbabfSVSSUOrTC4r +bnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQX5Ucv+2rIrVls4W6ng+4reV6G4pQ +Oh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWrQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01 +y8hSyn+B/tlr0/cR7SXf+Of5pPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061 +lgeLKBObjBmNQSdJQO7e5iNEOdyhIta6A/I= +-----END CERTIFICATE----- + +Microsec e-Szigno Root CA 2009 +============================== +-----BEGIN CERTIFICATE----- +MIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYDVQQGEwJIVTER +MA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jv +c2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o +dTAeFw0wOTA2MTYxMTMwMThaFw0yOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UE +BwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUt +U3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvPkd6mJviZpWNwrZuuyjNA +fW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tccbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG +0IMZfcChEhyVbUr02MelTTMuhTlAdX4UfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKA +pxn1ntxVUwOXewdI/5n7N4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm +1HxdrtbCxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1+rUC +AwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBTLD8bf +QkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAbBgNVHREE +FDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqGSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0o +lZMEyL/azXm4Q5DwpL7v8u8hmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfX +I/OMn74dseGkddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775 +tyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c2Pm2G2JwCz02 +yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5tHMN1Rq41Bab2XD0h7lbwyYIi +LXpUq3DDfSJlgnCW +-----END CERTIFICATE----- + +GlobalSign Root CA - R3 +======================= +-----BEGIN CERTIFICATE----- +MIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4GA1UECxMXR2xv +YmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2Jh +bFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4MTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxT +aWduIFJvb3QgQ0EgLSBSMzETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2ln +bjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWt +iHL8RgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsTgHeMCOFJ +0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmmKPZpO/bLyCiR5Z2KYVc3 +rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zdQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjl +OCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2 +xmmFghcCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE +FI/wS3+oLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZURUm7 +lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMpjjM5RcOO5LlXbKr8 +EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK6fBdRoyV3XpYKBovHd7NADdBj+1E +bddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQXmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18 +YIvDQVETI53O9zJrlAGomecsMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7r +kpeDMdmztcpHWD9f +-----END CERTIFICATE----- + +Autoridad de Certificacion Firmaprofesional CIF A62634068 +========================================================= +-----BEGIN CERTIFICATE----- +MIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UEBhMCRVMxQjBA +BgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1hcHJvZmVzaW9uYWwgQ0lGIEE2 +MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEyMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIw +QAYDVQQDDDlBdXRvcmlkYWQgZGUgQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBB +NjI2MzQwNjgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDD +Utd9thDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQMcas9UX4P +B99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefGL9ItWY16Ck6WaVICqjaY +7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15iNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqH +ECNZXyAFGUftaI6SEspd/NYrspI8IM/hX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyI +plD9amML9ZMWGxmPsu2bm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctX +MbScyJCyZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirjaEbsX +LZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/TKI8xWVvTyQKmtFLK +bpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF6NkBiDkal4ZkQdU7hwxu+g/GvUgU +vzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVhOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1Ud +EwEB/wQIMAYBAf8CAQEwDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNH +DhpkLzCBpgYDVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp +cm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBvACAAZABlACAA +bABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBlAGwAbwBuAGEAIAAwADgAMAAx +ADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx +51tkljYyGOylMnfX40S2wBEqgLk9am58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qk +R71kMrv2JYSiJ0L1ILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaP +T481PyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS3a/DTg4f +Jl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5kSeTy36LssUzAKh3ntLFl +osS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF3dvd6qJ2gHN99ZwExEWN57kci57q13XR +crHedUTnQn3iV2t93Jm8PYMo6oCTjcVMZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoR +saS8I8nkvof/uZS2+F0gStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTD +KCOM/iczQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQBjLMi +6Et8Vcad+qMUu2WFbm5PEn4KPJ2V +-----END CERTIFICATE----- + +Izenpe.com +========== +-----BEGIN CERTIFICATE----- +MIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4MQswCQYDVQQG +EwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wHhcNMDcxMjEz +MTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMu +QS4xEzARBgNVBAMMCkl6ZW5wZS5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ +03rKDx6sp4boFmVqscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAK +ClaOxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6HLmYRY2xU ++zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFXuaOKmMPsOzTFlUFpfnXC +PCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQDyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxT +OTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+JrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbK +F7jJeodWLBoBHmy+E60QrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK +0GqfvEyNBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8Lhij+ +0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIBQFqNeb+Lz0vPqhbB +leStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+HMh3/1uaD7euBUbl8agW7EekFwID +AQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2luZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+ +SVpFTlBFIFMuQS4gLSBDSUYgQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBG +NjIgUzgxQzBBBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx +MCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O +BBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUAA4ICAQB4pgwWSp9MiDrAyw6l +Fn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWblaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbga +kEyrkgPH7UIBzg/YsfqikuFgba56awmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8q +hT/AQKM6WfxZSzwoJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Cs +g1lwLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCTVyvehQP5 +aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGkLhObNA5me0mrZJfQRsN5 +nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJbUjWumDqtujWTI6cfSN01RpiyEGjkpTHC +ClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/QnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZo +Q0iy2+tzJOeRf1SktoA+naM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1Z +WrOZyGlsQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw== +-----END CERTIFICATE----- + +Chambers of Commerce Root - 2008 +================================ +-----BEGIN CERTIFICATE----- +MIIHTzCCBTegAwIBAgIJAKPaQn6ksa7aMA0GCSqGSIb3DQEBBQUAMIGuMQswCQYDVQQGEwJFVTFD +MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv +bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu +QS4xKTAnBgNVBAMTIENoYW1iZXJzIG9mIENvbW1lcmNlIFJvb3QgLSAyMDA4MB4XDTA4MDgwMTEy +Mjk1MFoXDTM4MDczMTEyMjk1MFowga4xCzAJBgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNl +ZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNhbWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQF +EwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENhbWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJl +cnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDgwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC +AQCvAMtwNyuAWko6bHiUfaN/Gh/2NdW928sNRHI+JrKQUrpjOyhYb6WzbZSm891kDFX29ufyIiKA +XuFixrYp4YFs8r/lfTJqVKAyGVn+H4vXPWCGhSRv4xGzdz4gljUha7MI2XAuZPeEklPWDrCQiorj +h40G072QDuKZoRuGDtqaCrsLYVAGUvGef3bsyw/QHg3PmTA9HMRFEFis1tPo1+XqxQEHd9ZR5gN/ +ikilTWh1uem8nk4ZcfUyS5xtYBkL+8ydddy/Js2Pk3g5eXNeJQ7KXOt3EgfLZEFHcpOrUMPrCXZk +NNI5t3YRCQ12RcSprj1qr7V9ZS+UWBDsXHyvfuK2GNnQm05aSd+pZgvMPMZ4fKecHePOjlO+Bd5g +D2vlGts/4+EhySnB8esHnFIbAURRPHsl18TlUlRdJQfKFiC4reRB7noI/plvg6aRArBsNlVq5331 +lubKgdaX8ZSD6e2wsWsSaR6s+12pxZjptFtYer49okQ6Y1nUCyXeG0+95QGezdIp1Z8XGQpvvwyQ +0wlf2eOKNcx5Wk0ZN5K3xMGtr/R5JJqyAQuxr1yW84Ay+1w9mPGgP0revq+ULtlVmhduYJ1jbLhj +ya6BXBg14JC7vjxPNyK5fuvPnnchpj04gftI2jE9K+OJ9dC1vX7gUMQSibMjmhAxhduub+84Mxh2 +EQIDAQABo4IBbDCCAWgwEgYDVR0TAQH/BAgwBgEB/wIBDDAdBgNVHQ4EFgQU+SSsD7K1+HnA+mCI +G8TZTQKeFxkwgeMGA1UdIwSB2zCB2IAU+SSsD7K1+HnA+mCIG8TZTQKeFxmhgbSkgbEwga4xCzAJ +BgNVBAYTAkVVMUMwQQYDVQQHEzpNYWRyaWQgKHNlZSBjdXJyZW50IGFkZHJlc3MgYXQgd3d3LmNh +bWVyZmlybWEuY29tL2FkZHJlc3MpMRIwEAYDVQQFEwlBODI3NDMyODcxGzAZBgNVBAoTEkFDIENh +bWVyZmlybWEgUy5BLjEpMCcGA1UEAxMgQ2hhbWJlcnMgb2YgQ29tbWVyY2UgUm9vdCAtIDIwMDiC +CQCj2kJ+pLGu2jAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUH +AgEWHGh0dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAJASryI1 +wqM58C7e6bXpeHxIvj99RZJe6dqxGfwWPJ+0W2aeaufDuV2I6A+tzyMP3iU6XsxPpcG1Lawk0lgH +3qLPaYRgM+gQDROpI9CF5Y57pp49chNyM/WqfcZjHwj0/gF/JM8rLFQJ3uIrbZLGOU8W6jx+ekbU +RWpGqOt1glanq6B8aBMz9p0w8G8nOSQjKpD9kCk18pPfNKXG9/jvjA9iSnyu0/VU+I22mlaHFoI6 +M6taIgj3grrqLuBHmrS1RaMFO9ncLkVAO+rcf+g769HsJtg1pDDFOqxXnrN2pSB7+R5KBWIBpih1 +YJeSDW4+TTdDDZIVnBgizVGZoCkaPF+KMjNbMMeJL0eYD6MDxvbxrN8y8NmBGuScvfaAFPDRLLmF +9dijscilIeUcE5fuDr3fKanvNFNb0+RqE4QGtjICxFKuItLcsiFCGtpA8CnJ7AoMXOLQusxI0zcK +zBIKinmwPQN/aUv0NCB9szTqjktk9T79syNnFQ0EuPAtwQlRPLJsFfClI9eDdOTlLsn+mCdCxqvG +nrDQWzilm1DefhiYtUU79nm06PcaewaD+9CL2rvHvRirCG88gGtAPxkZumWK5r7VXNM21+9AUiRg +OGcEMeyP84LG3rlV8zsxkVrctQgVrXYlCg17LofiDKYGvCYQbTed7N14jHyAxfDZd0jQ +-----END CERTIFICATE----- + +Global Chambersign Root - 2008 +============================== +-----BEGIN CERTIFICATE----- +MIIHSTCCBTGgAwIBAgIJAMnN0+nVfSPOMA0GCSqGSIb3DQEBBQUAMIGsMQswCQYDVQQGEwJFVTFD +MEEGA1UEBxM6TWFkcmlkIChzZWUgY3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNv +bS9hZGRyZXNzKTESMBAGA1UEBRMJQTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMu +QS4xJzAlBgNVBAMTHkdsb2JhbCBDaGFtYmVyc2lnbiBSb290IC0gMjAwODAeFw0wODA4MDExMjMx +NDBaFw0zODA3MzExMjMxNDBaMIGsMQswCQYDVQQGEwJFVTFDMEEGA1UEBxM6TWFkcmlkIChzZWUg +Y3VycmVudCBhZGRyZXNzIGF0IHd3dy5jYW1lcmZpcm1hLmNvbS9hZGRyZXNzKTESMBAGA1UEBRMJ +QTgyNzQzMjg3MRswGQYDVQQKExJBQyBDYW1lcmZpcm1hIFMuQS4xJzAlBgNVBAMTHkdsb2JhbCBD +aGFtYmVyc2lnbiBSb290IC0gMjAwODCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDf +VtPkOpt2RbQT2//BthmLN0EYlVJH6xedKYiONWwGMi5HYvNJBL99RDaxccy9Wglz1dmFRP+RVyXf +XjaOcNFccUMd2drvXNL7G706tcuto8xEpw2uIRU/uXpbknXYpBI4iRmKt4DS4jJvVpyR1ogQC7N0 +ZJJ0YPP2zxhPYLIj0Mc7zmFLmY/CDNBAspjcDahOo7kKrmCgrUVSY7pmvWjg+b4aqIG7HkF4ddPB +/gBVsIdU6CeQNR1MM62X/JcumIS/LMmjv9GYERTtY/jKmIhYF5ntRQOXfjyGHoiMvvKRhI9lNNgA +TH23MRdaKXoKGCQwoze1eqkBfSbW+Q6OWfH9GzO1KTsXO0G2Id3UwD2ln58fQ1DJu7xsepeY7s2M +H/ucUa6LcL0nn3HAa6x9kGbo1106DbDVwo3VyJ2dwW3Q0L9R5OP4wzg2rtandeavhENdk5IMagfe +Ox2YItaswTXbo6Al/3K1dh3ebeksZixShNBFks4c5eUzHdwHU1SjqoI7mjcv3N2gZOnm3b2u/GSF +HTynyQbehP9r6GsaPMWis0L7iwk+XwhSx2LE1AVxv8Rk5Pihg+g+EpuoHtQ2TS9x9o0o9oOpE9Jh +wZG7SMA0j0GMS0zbaRL/UJScIINZc+18ofLx/d33SdNDWKBWY8o9PeU1VlnpDsogzCtLkykPAgMB +AAGjggFqMIIBZjASBgNVHRMBAf8ECDAGAQH/AgEMMB0GA1UdDgQWBBS5CcqcHtvTbDprru1U8VuT +BjUuXjCB4QYDVR0jBIHZMIHWgBS5CcqcHtvTbDprru1U8VuTBjUuXqGBsqSBrzCBrDELMAkGA1UE +BhMCRVUxQzBBBgNVBAcTOk1hZHJpZCAoc2VlIGN1cnJlbnQgYWRkcmVzcyBhdCB3d3cuY2FtZXJm +aXJtYS5jb20vYWRkcmVzcykxEjAQBgNVBAUTCUE4Mjc0MzI4NzEbMBkGA1UEChMSQUMgQ2FtZXJm +aXJtYSBTLkEuMScwJQYDVQQDEx5HbG9iYWwgQ2hhbWJlcnNpZ24gUm9vdCAtIDIwMDiCCQDJzdPp +1X0jzjAOBgNVHQ8BAf8EBAMCAQYwPQYDVR0gBDYwNDAyBgRVHSAAMCowKAYIKwYBBQUHAgEWHGh0 +dHA6Ly9wb2xpY3kuY2FtZXJmaXJtYS5jb20wDQYJKoZIhvcNAQEFBQADggIBAICIf3DekijZBZRG +/5BXqfEv3xoNa/p8DhxJJHkn2EaqbylZUohwEurdPfWbU1Rv4WCiqAm57OtZfMY18dwY6fFn5a+6 +ReAJ3spED8IXDneRRXozX1+WLGiLwUePmJs9wOzL9dWCkoQ10b42OFZyMVtHLaoXpGNR6woBrX/s +dZ7LoR/xfxKxueRkf2fWIyr0uDldmOghp+G9PUIadJpwr2hsUF1Jz//7Dl3mLEfXgTpZALVza2Mg +9jFFCDkO9HB+QHBaP9BrQql0PSgvAm11cpUJjUhjxsYjV5KTXjXBjfkK9yydYhz2rXzdpjEetrHH +foUm+qRqtdpjMNHvkzeyZi99Bffnt0uYlDXA2TopwZ2yUDMdSqlapskD7+3056huirRXhOukP9Du +qqqHW2Pok+JrqNS4cnhrG+055F3Lm6qH1U9OAP7Zap88MQ8oAgF9mOinsKJknnn4SPIVqczmyETr +P3iZ8ntxPjzxmKfFGBI/5rsoM0LpRQp8bfKGeS/Fghl9CYl8slR2iK7ewfPM4W7bMdaTrpmg7yVq +c5iJWzouE4gev8CSlDQb4ye3ix5vQv/n6TebUB0tovkC7stYWDpxvGjjqsGvHCgfotwjZT+B6q6Z +09gwzxMNTxXJhLynSC34MCN32EZLeW32jO06f2ARePTpm67VVMB0gNELQp/B +-----END CERTIFICATE----- + +Go Daddy Root Certificate Authority - G2 +======================================== +-----BEGIN CERTIFICATE----- +MIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoTEUdvRGFkZHkuY29tLCBJbmMu +MTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5 +MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6 +b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8G +A1UEAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKDE6bFIEMBO4Tx5oVJnyfq +9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD ++qK+ihVqf94Lw7YZFAXK6sOoBJQ7RnwyDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutd +fMh8+7ArU6SSYmlRJQVhGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMl +NAJWJwGRtDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFDqahQcQZyi27/a9 +BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmXWWcDYfF+OwYxdS2hII5PZYe096ac +vNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r +5N9ss4UXnT3ZJE95kTXWXwTrgIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYV +N8Gb5DKj7Tjo2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO +LPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI4uJEvlz36hz1 +-----END CERTIFICATE----- + +Starfield Root Certificate Authority - G2 +========================================= +-----BEGIN CERTIFICATE----- +MIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s +b2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVsZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0 +eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAw +DgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQg +VGVjaG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZpY2F0ZSBB +dXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL3twQP89o/8ArFv +W59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMgnLRJdzIpVv257IzdIvpy3Cdhl+72WoTs +bhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1HOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNk +N3mSwOxGXn/hbVNMYq/NHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7Nf +ZTD4p7dNdloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0HZbU +JtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0GCSqGSIb3DQEBCwUAA4IBAQARWfol +TwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjUsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx +4mcujJUDJi5DnUox9g61DLu34jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUw +F5okxBDgBPfg8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K +pL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1mMpYjn0q7pBZ +c2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0 +-----END CERTIFICATE----- + +Starfield Services Root Certificate Authority - G2 +================================================== +-----BEGIN CERTIFICATE----- +MIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMxEDAOBgNVBAgT +B0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoTHFN0YXJmaWVsZCBUZWNobm9s +b2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVsZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRl +IEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNV +BAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxT +dGFyZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2VydmljZXMg +Um9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20pOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2 +h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm28xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4Pa +hHQUw2eeBGg6345AWh1KTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLP +LJGmpufehRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk6mFB +rMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAwDwYDVR0TAQH/BAUw +AwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+qAdcwKziIorhtSpzyEZGDMA0GCSqG +SIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMIbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPP +E95Dz+I0swSdHynVv/heyNXBve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTy +xQGjhdByPq1zqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd +iEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn0q23KXB56jza +YyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCNsSi6 +-----END CERTIFICATE----- + +AffirmTrust Commercial +====================== +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMB4XDTEw +MDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly +bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6Eqdb +DuKPHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yrba0F8PrV +C8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPALMeIrJmqbTFeurCA+ukV6 +BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1yHp52UKqK39c/s4mT6NmgTWvRLpUHhww +MmWd5jyTXlBOeuM61G7MGvv50jeuJCqrVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNV +HQ4EFgQUnZPGU4teyq8/nx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYGXUPG +hi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNjvbz4YYCanrHOQnDi +qX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivtZ8SOyUOyXGsViQK8YvxO8rUzqrJv +0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9gN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0kh +sUlHRUe072o0EclNmsxZt9YCnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8= +-----END CERTIFICATE----- + +AffirmTrust Networking +====================== +-----BEGIN CERTIFICATE----- +MIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMB4XDTEw +MDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmly +bVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SE +Hi3yYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbuakCNrmreI +dIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRLQESxG9fhwoXA3hA/Pe24 +/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gb +h+0t+nvujArjqWaJGctB+d1ENmHP4ndGyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNV +HQ4EFgQUBx/S55zawm6iQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AQYwDQYJKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfOtDIu +UFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzuQY0x2+c06lkh1QF6 +12S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZLgo/bNjR9eUJtGxUAArgFU2HdW23 +WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4uolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9 +/ZFvgrG+CJPbFEfxojfHRZ48x3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s= +-----END CERTIFICATE----- + +AffirmTrust Premium +=================== +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UEBhMCVVMxFDAS +BgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMB4XDTEwMDEy +OTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRy +dXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEAxBLfqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtn +BKAQJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ+jjeRFcV +5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrSs8PhaJyJ+HoAVt70VZVs ++7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5HMQxK9VfvFMSF5yZVylmd2EhMQcuJUmd +GPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d770O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5R +p9EixAqnOEhss/n/fauGV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NI +S+LI+H+SqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S5u04 +6uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4IaC1nEWTJ3s7xgaVY5 +/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TXOwF0lkLgAOIua+rF7nKsu7/+6qqo ++Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYEFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB +/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByv +MiPIs0laUZx2KI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg +Nt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B8OWycvpEgjNC +6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQMKSOyARiqcTtNd56l+0OOF6S +L5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK ++4w1IX2COPKpVJEZNZOUbWo6xbLQu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmV +BtWVyuEklut89pMFu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFg +IxpHYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8GKa1qF60 +g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaORtGdFNrHF+QFlozEJLUb +zxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6eKeC2uAloGRwYQw== +-----END CERTIFICATE----- + +AffirmTrust Premium ECC +======================= +-----BEGIN CERTIFICATE----- +MIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMCVVMxFDASBgNV +BAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQcmVtaXVtIEVDQzAeFw0xMDAx +MjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1U +cnVzdDEgMB4GA1UEAwwXQWZmaXJtVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQA +IgNiAAQNMF4bFZ0D0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQ +N8O9ss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0GA1UdDgQW +BBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAK +BggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/VsaobgxCd05DhT1wV/GzTjxi+zygk8N53X +57hG8f2h4nECMEJZh0PUUd+60wkyWs6Iflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKM +eQ== +-----END CERTIFICATE----- + +Certum Trusted Network CA +========================= +-----BEGIN CERTIFICATE----- +MIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBMMSIwIAYDVQQK +ExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBUcnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIy +MTIwNzM3WhcNMjkxMjMxMTIwNzM3WjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBU +ZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +MSIwIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rHUV+rpDKmYYe2bg+G0jAC +l/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LMTXPb865Px1bVWqeWifrzq2jUI4ZZJ88J +J7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVUBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4 +fOQtf/WsX+sWn7Et0brMkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0 +cvW0QM8xAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNVHRMB +Af8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNVHQ8BAf8EBAMCAQYw +DQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15ysHhE49wcrwn9I0j6vSrEuVUEtRCj +jSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfLI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1 +mS1FhIrlQgnXdAIv94nYmem8J9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5aj +Zt3hrvJBW8qYVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI +03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw= +-----END CERTIFICATE----- + +TWCA Root Certification Authority +================================= +-----BEGIN CERTIFICATE----- +MIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJ +VEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMzWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQG +EwJUVzESMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NB +IFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFEAcK0HMMx +QhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HHK3XLfJ+utdGdIzdjp9xC +oi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeXRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP +4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/zrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1r +y+UPizgN7gr8/g+YnzAx3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIB +BjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkqhkiG +9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeCMErJk/9q56YAf4lC +mtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdlsXebQ79NqZp4VKIV66IIArB6nCWlW +QtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62Dlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVY +T0bf+215WfKEIlKuD8z7fDvnaspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocny +Yh0igzyXxfkZYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw== +-----END CERTIFICATE----- + +Security Communication RootCA2 +============================== +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc +U0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMeU2VjdXJpdHkgQ29tbXVuaWNh +dGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoXDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMC +SlAxJTAjBgNVBAoTHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3Vy +aXR5IENvbW11bmljYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ANAVOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGrzbl+dp++ ++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVMVAX3NuRFg3sUZdbcDE3R +3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQhNBqyjoGADdH5H5XTz+L62e4iKrFvlNV +spHEfbmwhRkGeC7bYRr6hfVKkaHnFtWOojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1K +EOtOghY6rCcMU/Gt1SSwawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8 +QIH4D5csOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEB +CwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpFcoJxDjrSzG+ntKEj +u/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXcokgfGT+Ok+vx+hfuzU7jBBJV1uXk +3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6q +tnRGEmyR7jTV7JqR50S+kDFy1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29 +mvVXIwAHIRc/SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03 +-----END CERTIFICATE----- + +EC-ACC +====== +-----BEGIN CERTIFICATE----- +MIIFVjCCBD6gAwIBAgIQ7is969Qh3hSoYqwE893EATANBgkqhkiG9w0BAQUFADCB8zELMAkGA1UE +BhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2VydGlmaWNhY2lvIChOSUYgUS0w +ODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYD +VQQLEyxWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UE +CxMsSmVyYXJxdWlhIEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMT +BkVDLUFDQzAeFw0wMzAxMDcyMzAwMDBaFw0zMTAxMDcyMjU5NTlaMIHzMQswCQYDVQQGEwJFUzE7 +MDkGA1UEChMyQWdlbmNpYSBDYXRhbGFuYSBkZSBDZXJ0aWZpY2FjaW8gKE5JRiBRLTA4MDExNzYt +SSkxKDAmBgNVBAsTH1NlcnZlaXMgUHVibGljcyBkZSBDZXJ0aWZpY2FjaW8xNTAzBgNVBAsTLFZl +Z2V1IGh0dHBzOi8vd3d3LmNhdGNlcnQubmV0L3ZlcmFycmVsIChjKTAzMTUwMwYDVQQLEyxKZXJh +cnF1aWEgRW50aXRhdHMgZGUgQ2VydGlmaWNhY2lvIENhdGFsYW5lczEPMA0GA1UEAxMGRUMtQUND +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsyLHT+KXQpWIR4NA9h0X84NzJB5R85iK +w5K4/0CQBXCHYMkAqbWUZRkiFRfCQ2xmRJoNBD45b6VLeqpjt4pEndljkYRm4CgPukLjbo73FCeT +ae6RDqNfDrHrZqJyTxIThmV6PttPB/SnCWDaOkKZx7J/sxaVHMf5NLWUhdWZXqBIoH7nF2W4onW4 +HvPlQn2v7fOKSGRdghST2MDk/7NQcvJ29rNdQlB50JQ+awwAvthrDk4q7D7SzIKiGGUzE3eeml0a +E9jD2z3Il3rucO2n5nzbcc8tlGLfbdb1OL4/pYUKGbio2Al1QnDE6u/LDsg0qBIimAy4E5S2S+zw +0JDnJwIDAQABo4HjMIHgMB0GA1UdEQQWMBSBEmVjX2FjY0BjYXRjZXJ0Lm5ldDAPBgNVHRMBAf8E +BTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUoMOLRKo3pUW/l4Ba0fF4opvpXY0wfwYD +VR0gBHgwdjB0BgsrBgEEAfV4AQMBCjBlMCwGCCsGAQUFBwIBFiBodHRwczovL3d3dy5jYXRjZXJ0 +Lm5ldC92ZXJhcnJlbDA1BggrBgEFBQcCAjApGidWZWdldSBodHRwczovL3d3dy5jYXRjZXJ0Lm5l +dC92ZXJhcnJlbCAwDQYJKoZIhvcNAQEFBQADggEBAKBIW4IB9k1IuDlVNZyAelOZ1Vr/sXE7zDkJ +lF7W2u++AVtd0x7Y/X1PzaBB4DSTv8vihpw3kpBWHNzrKQXlxJ7HNd+KDM3FIUPpqojlNcAZQmNa +Al6kSBg6hW/cnbw/nZzBh7h6YQjpdwt/cKt63dmXLGQehb+8dJahw3oS7AwaboMMPOhyRp/7SNVe +l+axofjk70YllJyJ22k4vuxcDlbHZVHlUIiIv0LVKz3l+bqeLrPK9HOSAgu+TGbrIP65y7WZf+a2 +E/rKS03Z7lNGBjvGTq2TWoF+bCpLagVFjPIhpDGQh2xlnJ2lYJU6Un/10asIbvPuW/mIPX64b24D +5EI= +-----END CERTIFICATE----- + +Hellenic Academic and Research Institutions RootCA 2011 +======================================================= +-----BEGIN CERTIFICATE----- +MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1IxRDBCBgNVBAoT +O0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9y +aXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z +IFJvb3RDQSAyMDExMB4XDTExMTIwNjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYT +AkdSMUQwQgYDVQQKEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25z +IENlcnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNo +IEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPzdYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI +1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJfel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa +71HFK9+WXesyHgLacEnsbgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u +8yBRQlqD75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSPFEDH +3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNVHRMBAf8EBTADAQH/ +MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp5dgTBCPuQSUwRwYDVR0eBEAwPqA8 +MAWCAy5ncjAFggMuZXUwBoIELmVkdTAGggQub3JnMAWBAy5ncjAFgQMuZXUwBoEELmVkdTAGgQQu +b3JnMA0GCSqGSIb3DQEBBQUAA4IBAQAf73lB4XtuP7KMhjdCSk4cNx6NZrokgclPEg8hwAOXhiVt +XdMiKahsog2p6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 +TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7dIsXRSZMFpGD +/md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8AcysNnq/onN694/BtZqhFLKPM58N +7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXIl7WdmplNsDz4SgCbZN2fOUvRJ9e4 +-----END CERTIFICATE----- + +Actalis Authentication Root CA +============================== +-----BEGIN CERTIFICATE----- +MIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UEBhMCSVQxDjAM +BgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UE +AwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENBMB4XDTExMDkyMjExMjIwMloXDTMwMDky +MjExMjIwMlowazELMAkGA1UEBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlz +IFMucC5BLi8wMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290 +IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNvUTufClrJ +wkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX4ay8IMKx4INRimlNAJZa +by/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9KK3giq0itFZljoZUj5NDKd45RnijMCO6 +zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/gCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1f +YVEiVRvjRuPjPdA1YprbrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2 +oxgkg4YQ51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2Fbe8l +EfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxeKF+w6D9Fz8+vm2/7 +hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4Fv6MGn8i1zeQf1xcGDXqVdFUNaBr8 +EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbnfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5 +jF66CyCU3nuDuP/jVo23Eek7jPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLY +iDrIn3hm7YnzezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt +ifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQALe3KHwGCmSUyI +WOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70jsNjLiNmsGe+b7bAEzlgqqI0 +JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDzWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKx +K3JCaKygvU5a2hi/a5iB0P2avl4VSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+ +Xlff1ANATIGk0k9jpwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC +4yyXX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+OkfcvHlXHo +2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7RK4X9p2jIugErsWx0Hbhz +lefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btUZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXem +OR/qnuOf0GZvBeyqdn6/axag67XH/JJULysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9 +vwGYT7JZVEc+NHt4bVaTLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg== +-----END CERTIFICATE----- + +Trustis FPS Root CA +=================== +-----BEGIN CERTIFICATE----- +MIIDZzCCAk+gAwIBAgIQGx+ttiD5JNM2a/fH8YygWTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQG +EwJHQjEYMBYGA1UEChMPVHJ1c3RpcyBMaW1pdGVkMRwwGgYDVQQLExNUcnVzdGlzIEZQUyBSb290 +IENBMB4XDTAzMTIyMzEyMTQwNloXDTI0MDEyMTExMzY1NFowRTELMAkGA1UEBhMCR0IxGDAWBgNV +BAoTD1RydXN0aXMgTGltaXRlZDEcMBoGA1UECxMTVHJ1c3RpcyBGUFMgUm9vdCBDQTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAMVQe547NdDfxIzNjpvto8A2mfRC6qc+gIMPpqdZh8mQ +RUN+AOqGeSoDvT03mYlmt+WKVoaTnGhLaASMk5MCPjDSNzoiYYkchU59j9WvezX2fihHiTHcDnlk +H5nSW7r+f2C/revnPDgpai/lkQtV/+xvWNUtyd5MZnGPDNcE2gfmHhjjvSkCqPoc4Vu5g6hBSLwa +cY3nYuUtsuvffM/bq1rKMfFMIvMFE/eC+XN5DL7XSxzA0RU8k0Fk0ea+IxciAIleH2ulrG6nS4zt +o3Lmr2NNL4XSFDWaLk6M6jKYKIahkQlBOrTh4/L68MkKokHdqeMDx4gVOxzUGpTXn2RZEm0CAwEA +AaNTMFEwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBS6+nEleYtXQSUhhgtx67JkDoshZzAd +BgNVHQ4EFgQUuvpxJXmLV0ElIYYLceuyZA6LIWcwDQYJKoZIhvcNAQEFBQADggEBAH5Y//01GX2c +GE+esCu8jowU/yyg2kdbw++BLa8F6nRIW/M+TgfHbcWzk88iNVy2P3UnXwmWzaD+vkAMXBJV+JOC +yinpXj9WV4s4NvdFGkwozZ5BuO1WTISkQMi4sKUraXAEasP41BIy+Q7DsdwyhEQsb8tGD+pmQQ9P +8Vilpg0ND2HepZ5dfWWhPBfnqFVO76DH7cZEf1T1o+CP8HxVIo8ptoGj4W1OLBuAZ+ytIJ8MYmHV +l/9D7S3B2l0pKoU/rGXuhg8FjZBf3+6f9L/uHfuY5H+QK4R4EA5sSVPvFVtlRkpdr7r7OnIdzfYl +iB6XzCGcKQENZetX2fNXlrtIzYE= +-----END CERTIFICATE----- + +Buypass Class 2 Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMiBSb290IENBMB4X +DTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1owTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 +eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1 +g1Lr6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPVL4O2fuPn +9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC911K2GScuVr1QGbNgGE41b +/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHxMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqU +CqTqc/sLUegTBxj6DvEr0VQVfTzh97QZQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeff +awrbD02TTqigzXsu8lkBarcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgI +zRFo1clrUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLiFRhn +Bkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRSP/TizPJhk9H9Z2vX +Uq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN9SG9dKpN6nIDSdvHXx1iY8f93ZHs +M+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxPAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD +VR0OBBYEFMmAd+BikoL1RpzzuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF +AAOCAgEAU18h9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s +A20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3tOluwlN5E40EI +osHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo+fsicdl9sz1Gv7SEr5AcD48S +aq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7KcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYd +DnkM/crqJIByw5c/8nerQyIKx+u2DISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWD +LfJ6v9r9jv6ly0UsH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0 +oyLQI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK75t98biGC +wWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h3PFaTWwyI0PurKju7koS +CTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPzY11aWOIv4x3kqdbQCtCev9eBCfHJxyYN +rJgWVqA= +-----END CERTIFICATE----- + +Buypass Class 3 Root CA +======================= +-----BEGIN CERTIFICATE----- +MIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEdMBsGA1UECgwU +QnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3MgQ2xhc3MgMyBSb290IENBMB4X +DTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFowTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1 +eXBhc3MgQVMtOTgzMTYzMzI3MSAwHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIw +DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRH +sJ8YZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3EN3coTRiR +5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9tznDDgFHmV0ST9tD+leh +7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX0DJq1l1sDPGzbjniazEuOQAnFN44wOwZ +ZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH +2xc519woe2v1n/MuwU8XKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV +/afmiSTYzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvSO1UQ +RwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D34xFMFbG02SrZvPA +Xpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgPK9Dx2hzLabjKSWJtyNBjYt1gD1iq +j6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYD +VR0OBBYEFEe4zf/lb+74suwvTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsF +AAOCAgEAACAjQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV +cSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXSIGrs/CIBKM+G +uIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2HJLw5QY33KbmkJs4j1xrG0aG +Q0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsaO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8 +ZORK15FTAaggiG6cX0S5y2CBNOxv033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2 +KSb12tjE8nVhz36udmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz +6MkEkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg413OEMXbug +UZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvDu79leNKGef9JOxqDDPDe +eOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq4/g7u9xN12TyUb7mqqta6THuBrxzvxNi +Cp/HuZc= +-----END CERTIFICATE----- + +T-TeleSec GlobalRoot Class 3 +============================ +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM +IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU +cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgx +MDAxMTAyOTU2WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz +dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD +ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN8ELg63iIVl6bmlQdTQyK +9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/RLyTPWGrTs0NvvAgJ1gORH8EGoel15YU +NpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4hqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZF +iP0Zf3WHHx+xGwpzJFu5ZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W +0eDrXltMEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1A/d2O2GCahKqGFPr +AyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOyWL6ukK2YJ5f+AbGwUgC4TeQbIXQb +fsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzT +ucpH9sry9uetuUg/vBa3wW306gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7h +P0HHRwA11fXT91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml +e9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4pTpPDpFQUWw== +-----END CERTIFICATE----- + +EE Certification Centre Root CA +=============================== +-----BEGIN CERTIFICATE----- +MIIEAzCCAuugAwIBAgIQVID5oHPtPwBMyonY43HmSjANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQG +EwJFRTEiMCAGA1UECgwZQVMgU2VydGlmaXRzZWVyaW1pc2tlc2t1czEoMCYGA1UEAwwfRUUgQ2Vy +dGlmaWNhdGlvbiBDZW50cmUgUm9vdCBDQTEYMBYGCSqGSIb3DQEJARYJcGtpQHNrLmVlMCIYDzIw +MTAxMDMwMTAxMDMwWhgPMjAzMDEyMTcyMzU5NTlaMHUxCzAJBgNVBAYTAkVFMSIwIAYDVQQKDBlB +UyBTZXJ0aWZpdHNlZXJpbWlza2Vza3VzMSgwJgYDVQQDDB9FRSBDZXJ0aWZpY2F0aW9uIENlbnRy +ZSBSb290IENBMRgwFgYJKoZIhvcNAQkBFglwa2lAc2suZWUwggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQDIIMDs4MVLqwd4lfNE7vsLDP90jmG7sWLqI9iroWUyeuuOF0+W2Ap7kaJjbMeM +TC55v6kF/GlclY1i+blw7cNRfdCT5mzrMEvhvH2/UpvObntl8jixwKIy72KyaOBhU8E2lf/slLo2 +rpwcpzIP5Xy0xm90/XsY6KxX7QYgSzIwWFv9zajmofxwvI6Sc9uXp3whrj3B9UiHbCe9nyV0gVWw +93X2PaRka9ZP585ArQ/dMtO8ihJTmMmJ+xAdTX7Nfh9WDSFwhfYggx/2uh8Ej+p3iDXE/+pOoYtN +P2MbRMNE1CV2yreN1x5KZmTNXMWcg+HCCIia7E6j8T4cLNlsHaFLAgMBAAGjgYowgYcwDwYDVR0T +AQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFBLyWj7qVhy/zQas8fElyalL1BSZ +MEUGA1UdJQQ+MDwGCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEF +BQcDCAYIKwYBBQUHAwkwDQYJKoZIhvcNAQEFBQADggEBAHv25MANqhlHt01Xo/6tu7Fq1Q+e2+Rj +xY6hUFaTlrg4wCQiZrxTFGGVv9DHKpY5P30osxBAIWrEr7BSdxjhlthWXePdNl4dp1BUoMUq5KqM +lIpPnTX/dqQGE5Gion0ARD9V04I8GtVbvFZMIi5GQ4okQC3zErg7cBqklrkar4dBGmoYDQZPxz5u +uSlNDUmJEYcyW+ZLBMjkXOZ0c5RdFpgTlf7727FE5TpwrDdr5rMzcijJs1eg9gIWiAYLtqZLICjU +3j2LrTcFU3T+bsy8QxdxXvnFzBqpYe73dgzzcvRyrc9yAjYHR8/vGVCJYMzpJJUPwssd8m92kMfM +dcGWxZ0= +-----END CERTIFICATE----- + +D-TRUST Root Class 3 CA 2 2009 +============================== +-----BEGIN CERTIFICATE----- +MIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTAe +Fw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NThaME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxE +LVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOAD +ER03UAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42tSHKXzlA +BF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9RySPocq60vFYJfxLLHLGv +KZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsMlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7z +p+hnUquVH+BGPtikw8paxTGA6Eian5Rp/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUC +AwEAAaOCARowggEWMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ +4PGEMA4GA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVjdG9y +eS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUyMENBJTIwMiUyMDIw +MDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRlcmV2b2NhdGlvbmxpc3QwQ6BBoD+G +PWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3JsL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAw +OS5jcmwwDQYJKoZIhvcNAQELBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm +2H6NMLVwMeniacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0 +o3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4KzCUqNQT4YJEV +dT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8PIWmawomDeCTmGCufsYkl4ph +X5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3YJohw1+qRzT65ysCQblrGXnRl11z+o+I= +-----END CERTIFICATE----- + +D-TRUST Root Class 3 CA 2 EV 2009 +================================= +-----BEGIN CERTIFICATE----- +MIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw +OTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUwNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQK +DAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAw +OTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfS +egpnljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM03TP1YtHh +zRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6ZqQTMFexgaDbtCHu39b+T +7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lRp75mpoo6Kr3HGrHhFPC+Oh25z1uxav60 +sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8HgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure35 +11H3a6UCAwEAAaOCASQwggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyv +cop9NteaHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFwOi8v +ZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xhc3MlMjAzJTIwQ0El +MjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1ERT9jZXJ0aWZpY2F0ZXJldm9jYXRp +b25saXN0MEagRKBChkBodHRwOi8vd3d3LmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xh +c3NfM19jYV8yX2V2XzIwMDkuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+ +PPoeUSbrh/Yp3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05 +nsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNFCSuGdXzfX2lX +ANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7naxpeG0ILD5EJt/rDiZE4OJudA +NCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqXKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVv +w9y4AyHqnxbxLFS1 +-----END CERTIFICATE----- + +CA Disig Root R2 +================ +-----BEGIN CERTIFICATE----- +MIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNVBAYTAlNLMRMw +EQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMuMRkwFwYDVQQDExBDQSBEaXNp +ZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQyMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sx +EzARBgNVBAcTCkJyYXRpc2xhdmExEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERp +c2lnIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbC +w3OeNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNHPWSb6Wia +xswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3Ix2ymrdMxp7zo5eFm1tL7 +A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbeQTg06ov80egEFGEtQX6sx3dOy1FU+16S +GBsEWmjGycT6txOgmLcRK7fWV8x8nhfRyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqV +g8NTEQxzHQuyRpDRQjrOQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa +5Beny912H9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJQfYE +koopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUDi/ZnWejBBhG93c+A +Ak9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORsnLMOPReisjQS1n6yqEm70XooQL6i +Fh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1rqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNV +HRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5u +Qu0wDQYJKoZIhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM +tCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqfGopTpti72TVV +sRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkblvdhuDvEK7Z4bLQjb/D907Je +dR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W8 +1k/BfDxujRNt+3vrMNDcTa/F1balTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjx +mHHEt38OFdAlab0inSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01 +utI3gzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18DrG5gPcFw0 +sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3OszMOl6W8KjptlwlCFtaOg +UxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8xL4ysEr3vQCj8KWefshNPZiTEUxnpHikV +7+ZtsH8tZ/3zbBt1RqPlShfppNcL +-----END CERTIFICATE----- + +ACCVRAIZ1 +========= +-----BEGIN CERTIFICATE----- +MIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UEAwwJQUNDVlJB +SVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQswCQYDVQQGEwJFUzAeFw0xMTA1 +MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwH +UEtJQUNDVjENMAsGA1UECgwEQUNDVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQCbqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gM +jmoYHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWoG2ioPej0 +RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpAlHPrzg5XPAOBOp0KoVdD +aaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhrIA8wKFSVf+DuzgpmndFALW4ir50awQUZ +0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDG +WuzndN9wrqODJerWx5eHk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs7 +8yM2x/474KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMOm3WR +5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpacXpkatcnYGMN285J +9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPluUsXQA+xtrn13k/c4LOsOxFwYIRK +Q26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYIKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRw +Oi8vd3d3LmFjY3YuZXMvZmlsZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEu +Y3J0MB8GCCsGAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2 +VuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeTVfZW6oHlNsyM +Hj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIGCCsGAQUFBwICMIIBFB6CARAA +QQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUAcgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBh +AO0AegAgAGQAZQAgAGwAYQAgAEEAQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUA +YwBuAG8AbABvAGcA7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBj +AHQAcgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAAQwBQAFMA +IABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUAczAwBggrBgEFBQcCARYk +aHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2MuaHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0 +dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRtaW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2 +MV9kZXIuY3JsMA4GA1UdDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZI +hvcNAQEFBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdpD70E +R9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gUJyCpZET/LtZ1qmxN +YEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+mAM/EKXMRNt6GGT6d7hmKG9Ww7Y49 +nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepDvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJ +TS+xJlsndQAJxGJ3KQhfnlmstn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3 +sCPdK6jT2iWH7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h +I6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szAh1xA2syVP1Xg +Nce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xFd3+YJ5oyXSrjhO7FmGYvliAd +3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2HpPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3p +EfbRD0tVNEYqi4Y7 +-----END CERTIFICATE----- + +TWCA Global Root CA +=================== +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcxEjAQBgNVBAoT +CVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMTVFdDQSBHbG9iYWwgUm9vdCBD +QTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5NTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQK +EwlUQUlXQU4tQ0ExEDAOBgNVBAsTB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3Qg +Q0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2C +nJfF10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz0ALfUPZV +r2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfChMBwqoJimFb3u/Rk28OKR +Q4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbHzIh1HrtsBv+baz4X7GGqcXzGHaL3SekV +tTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1W +KKD+u4ZqyPpcC1jcxkt2yKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99 +sy2sbZCilaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYPoA/p +yJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQABDzfuBSO6N+pjWxn +kjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcEqYSjMq+u7msXi7Kx/mzhkIyIqJdI +zshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMC +AQYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6g +cFGn90xHNcgL1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn +LhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WFH6vPNOw/KP4M +8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNoRI2T9GRwoD2dKAXDOXC4Ynsg +/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+nile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlg +lPx4mI88k1HtQJAH32RjJMtOcQWh15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryP +A9gK8kxkRr05YuWW6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3m +i4TWnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5jwa19hAM8 +EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWzaGHQRiapIVJpLesux+t3 +zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmyKwbQBM0= +-----END CERTIFICATE----- + +TeliaSonera Root CA v1 +====================== +-----BEGIN CERTIFICATE----- +MIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAwNzEUMBIGA1UE +CgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJvb3QgQ0EgdjEwHhcNMDcxMDE4 +MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYDVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwW +VGVsaWFTb25lcmEgUm9vdCBDQSB2MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+ +6yfwIaPzaSZVfp3FVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA +3GV17CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+XZ75Ljo1k +B1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+/jXh7VB7qTCNGdMJjmhn +Xb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxH +oLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkmdtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3 +F0fUTPHSiXk+TT2YqGHeOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJ +oWjiUIMusDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4pgd7 +gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fsslESl1MpWtTwEhDc +TwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQarMCpgKIv7NHfirZ1fpoeDVNAgMB +AAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qW +DNXr+nuqF+gTEjANBgkqhkiG9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNm +zqjMDfz1mgbldxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx +0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1TjTQpgcmLNkQfW +pb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBedY2gea+zDTYa4EzAvXUYNR0PV +G6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7Q4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpc +c41teyWRyu5FrgZLAMzTsVlQ2jqIOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOT +JsjrDNYmiLbAJM+7vVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2 +qReWt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcnHL/EVlP6 +Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVxSK236thZiNSQvxaz2ems +WWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY= +-----END CERTIFICATE----- + +E-Tugra Certification Authority +=============================== +-----BEGIN CERTIFICATE----- +MIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNVBAYTAlRSMQ8w +DQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamls +ZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN +ZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMw +NTEyMDk0OFoXDTIzMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmEx +QDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxl +cmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQD +DB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEA4vU/kwVRHoViVF56C/UYB4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vd +hQd2h8y/L5VMzH2nPbxHD5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5K +CKpbknSFQ9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEoq1+g +ElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3Dk14opz8n8Y4e0ypQ +BaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcHfC425lAcP9tDJMW/hkd5s3kc91r0 +E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsutdEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gz +rt48Ue7LE3wBf4QOXVGUnhMMti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAq +jqFGOjGY5RH8zLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn +rFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUXU8u3Zg5mTPj5 +dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6Jyr+zE7S6E5UMA8GA1UdEwEB +/wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5XPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEG +MA0GCSqGSIb3DQEBCwUAA4ICAQAFNzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAK +kEh47U6YA5n+KGCRHTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jO +XKqYGwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c77NCR807 +VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3+GbHeJAAFS6LrVE1Uweo +a2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WKvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCc +dlqMQ1DujjByTd//SffGqWfZbawCEeI6FiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEV +KV0jq9BgoRJP3vQXzTLlyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gT +Dx4JnW2PAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpDy4Q0 +8ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8dNL/+I5c30jn6PQ0G +C7TbO6Orb1wdtn7os4I07QZcJA== +-----END CERTIFICATE----- + +T-TeleSec GlobalRoot Class 2 +============================ +-----BEGIN CERTIFICATE----- +MIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoM +IlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBU +cnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgx +MDAxMTA0MDE0WhcNMzMxMDAxMjM1OTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lz +dGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBD +ZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUdAqSzm1nzHoqvNK38DcLZ +SBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiCFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/F +vudocP05l03Sx5iRUKrERLMjfTlH6VJi1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx970 +2cu+fjOlbpSD8DT6IavqjnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGV +WOHAD3bZwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGjQjBA +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/WSA2AHmgoCJrjNXy +YdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhyNsZt+U2e+iKo4YFWz827n+qrkRk4 +r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPACuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNf +vNoBYimipidx5joifsFvHZVwIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR +3p1m0IvVVGb6g1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN +9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlPBSeOE6Fuwg== +-----END CERTIFICATE----- + +Atos TrustedRoot 2011 +===================== +-----BEGIN CERTIFICATE----- +MIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UEAwwVQXRvcyBU +cnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQGEwJERTAeFw0xMTA3MDcxNDU4 +MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMMFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsG +A1UECgwEQXRvczELMAkGA1UEBhMCREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCV +hTuXbyo7LjvPpvMpNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr +54rMVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+SZFhyBH+ +DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ4J7sVaE3IqKHBAUsR320 +HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0Lcp2AMBYHlT8oDv3FdU9T1nSatCQujgKR +z3bFmx5VdJx4IbHwLfELn8LVlhgf8FQieowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7R +l+lwrrw7GWzbITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZ +bNshMBgGA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB +CwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8jvZfza1zv7v1Apt+h +k6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kPDpFrdRbhIfzYJsdHt6bPWHJxfrrh +TZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pcmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a9 +61qn8FYiqTxlVMYVqL2Gns2Dlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G +3mB/ufNPRJLvKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed +-----END CERTIFICATE----- + +QuoVadis Root CA 1 G3 +===================== +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQELBQAwSDELMAkG +A1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAcBgNVBAMTFVF1b1ZhZGlzIFJv +b3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00MjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJN +MRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEg +RzMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakE +PBtVwedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWerNrwU8lm +PNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF34168Xfuw6cwI2H44g4hWf6 +Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh4Pw5qlPafX7PGglTvF0FBM+hSo+LdoIN +ofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXpUhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/l +g6AnhF4EwfWQvTA9xO+oabw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV +7qJZjqlc3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/GKubX +9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSthfbZxbGL0eUQMk1f +iyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KOTk0k+17kBL5yG6YnLUlamXrXXAkg +t3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOtzCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZI +hvcNAQELBQADggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC +MTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2cDMT/uFPpiN3 +GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUNqXsCHKnQO18LwIE6PWThv6ct +Tr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5YCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP ++V04ikkwj+3x6xn0dxoxGE1nVGwvb2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh +3jRJjehZrJ3ydlo28hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fa +wx/kNSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNjZgKAvQU6 +O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhpq1467HxpvMc7hU6eFbm0 +FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFtnh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOV +hMJKzRwuJIczYOXD +-----END CERTIFICATE----- + +QuoVadis Root CA 2 G3 +===================== +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQELBQAwSDELMAkG +A1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAcBgNVBAMTFVF1b1ZhZGlzIFJv +b3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00MjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJN +MRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIg +RzMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFh +ZiFfqq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMWn4rjyduY +NM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ymc5GQYaYDFCDy54ejiK2t +oIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+O7q414AB+6XrW7PFXmAqMaCvN+ggOp+o +MiwMzAkd056OXbxMmO7FGmh77FOm6RQ1o9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+l +V0POKa2Mq1W/xPtbAd0jIaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZo +L1NesNKqIcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz8eQQ +sSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43ehvNURG3YBZwjgQQvD +6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l7ZizlWNof/k19N+IxWA1ksB8aRxh +lRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALGcC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZI +hvcNAQELBQADggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66 +AarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RCroijQ1h5fq7K +pVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0GaW/ZZGYjeVYg3UQt4XAoeo0L9 +x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4nlv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgz +dWqTHBLmYF5vHX/JHyPLhGGfHoJE+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6X +U/IyAgkwo1jwDQHVcsaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+Nw +mNtddbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNgKCLjsZWD +zYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeMHVOyToV7BjjHLPj4sHKN +JeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4WSr2Rz0ZiC3oheGe7IUIarFsNMkd7Egr +O3jtZsSOeWmD3n+M +-----END CERTIFICATE----- + +QuoVadis Root CA 3 G3 +===================== +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQELBQAwSDELMAkG +A1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAcBgNVBAMTFVF1b1ZhZGlzIFJv +b3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00MjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJN +MRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMg +RzMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286 +IxSR/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNuFoM7pmRL +Mon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXRU7Ox7sWTaYI+FrUoRqHe +6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+cra1AdHkrAj80//ogaX3T7mH1urPnMNA3 +I4ZyYUUpSFlob3emLoG+B01vr87ERRORFHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3U +VDmrJqMz6nWB2i3ND0/kA9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f7 +5li59wzweyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634RylsSqi +Md5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBpVzgeAVuNVejH38DM +dyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0QA4XN8f+MFrXBsj6IbGB/kE+V9/Yt +rQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+ydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZI +hvcNAQELBQADggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px +KGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnIFUBhynLWcKzS +t/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5WvvoxXqA/4Ti2Tk08HS6IT7SdEQ +TXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFgu/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9Du +DcpmvJRPpq3t/O5jrFc/ZSXPsoaP0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGib +Ih6BJpsQBJFxwAYf3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmD +hPbl8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+DhcI00iX +0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HNPlopNLk9hM6xZdRZkZFW +dSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/ywaZWWDYWGWVjUTR939+J399roD1B0y2 +PpxxVJkES/1Y+Zj0 +-----END CERTIFICATE----- + +DigiCert Assured ID Root G2 +=========================== +-----BEGIN CERTIFICATE----- +MIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBlMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQw +IgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgw +MTE1MTIwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL +ExB3d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIw +ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSAn61UQbVH +35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4HteccbiJVMWWXvdMX0h5i89vq +bFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9HpEgjAALAcKxHad3A2m67OeYfcgnDmCXRw +VWmvo2ifv922ebPynXApVfSr/5Vh88lAbx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OP +YLfykqGxvYmJHzDNw6YuYjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+Rn +lTGNAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBTO +w0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPIQW5pJ6d1Ee88hjZv +0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I0jJmwYrA8y8678Dj1JGG0VDjA9tz +d29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4GnilmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAW +hsI6yLETcDbYz+70CjTVW0z9B5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0M +jomZmWzwPDCvON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo +IhNzbM8m9Yop5w== +-----END CERTIFICATE----- + +DigiCert Assured ID Root G3 +=========================== +-----BEGIN CERTIFICATE----- +MIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSQwIgYD +VQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1 +MTIwMDAwWjBlMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQ +BgcqhkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJfZn4f5dwb +RXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17QRSAPWXYQ1qAk8C3eNvJs +KTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgF +UaFNN6KDec6NHSrkhDAKBggqhkjOPQQDAwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5Fy +YZ5eEJJZVrmDxxDnOOlYJjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy +1vUhZscv6pZjamVFkpUBtA== +-----END CERTIFICATE----- + +DigiCert Global Root G2 +======================= +-----BEGIN CERTIFICATE----- +MIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAw +HgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUx +MjAwMDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3 +dy5kaWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkq +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI2/Ou8jqJ +kTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx1x7e/dfgy5SDN67sH0NO +3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQq2EGnI/yuum06ZIya7XzV+hdG82MHauV +BJVJ8zUtluNJbd134/tJS7SsVQepj5WztCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyM +UNGPHgm+F6HmIcr9g+UQvIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQAB +o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV5uNu +5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY1Yl9PMWLSn/pvtsr +F9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4NeF22d+mQrvHRAiGfzZ0JFrabA0U +WTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NGFdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBH +QRFXGU7Aj64GxJUTFy8bJZ918rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/ +iyK5S9kJRaTepLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl +MrY= +-----END CERTIFICATE----- + +DigiCert Global Root G3 +======================= +-----BEGIN CERTIFICATE----- +MIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQswCQYDVQQGEwJV +UzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSAwHgYD +VQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAw +MDBaMGExCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5k +aWdpY2VydC5jb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0C +AQYFK4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FGfp4tn+6O +YwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPOZ9wj/wMco+I+o0IwQDAP +BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNp +Yim8S8YwCgYIKoZIzj0EAwMDaAAwZQIxAK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y +3maTD/HMsQmP3Wyr+mt/oAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34 +VOKa5Vt8sycX +-----END CERTIFICATE----- + +DigiCert Trusted Root G4 +======================== +-----BEGIN CERTIFICATE----- +MIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBiMQswCQYDVQQG +EwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSEw +HwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1 +MTIwMDAwWjBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 +d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0G +CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3yithZwuEp +pz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1Ifxp4VpX6+n6lXFllVcq9o +k3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDVySAdYyktzuxeTsiT+CFhmzTrBcZe7Fsa +vOvJz82sNEBfsXpm7nfISKhmV1efVFiODCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGY +QJB5w3jHtrHEtWoYOAMQjdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6 +MUSaM0C/CNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCiEhtm +mnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADMfRyVw4/3IbKyEbe7 +f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QYuKZ3AeEPlAwhHbJUKSWJbOUOUlFH +dL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXKchYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8 +oR7FwI+isX4KJpn15GkvmB0t9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud +DwEB/wQEAwIBhjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD +ggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2SV1EY+CtnJYY +ZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd+SeuMIW59mdNOj6PWTkiU0Tr +yF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWcfFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy +7zBZLq7gcfJW5GqXb5JQbZaNaHqasjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iah +ixTXTBmyUEFxPT9NcCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN +5r5N0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie4u1Ki7wb +/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mIr/OSmbaz5mEP0oUA51Aa +5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tK +G48BtieVU+i2iW1bvGjUI+iLUaJW+fCmgKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP +82Z+ +-----END CERTIFICATE----- + +COMODO RSA Certification Authority +================================== +-----BEGIN CERTIFICATE----- +MIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCBhTELMAkGA1UE +BhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgG +A1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwHhcNMTAwMTE5MDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMC +R0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UE +ChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBB +dXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR6FSS0gpWsawNJN3Fz0Rn +dJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8Xpz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZ +FGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+ +5eNu/Nio5JIk2kNrYrhV/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pG +x8cgoLEfZd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z+pUX +2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7wqP/0uK3pN/u6uPQL +OvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZahSL0896+1DSJMwBGB7FY79tOi4lu3 +sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVICu9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+C +GCe01a60y1Dma/RMhnEw6abfFobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5 +WdYgGq/yapiqcrxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E +FgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8w +DQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvlwFTPoCWOAvn9sKIN9SCYPBMt +rFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+ +nq6PK7o9mfjYcwlYRm6mnPTXJ9OV2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSg +tZx8jb8uk2IntznaFxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwW +sRqZCuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiKboHGhfKp +pC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmckejkk9u+UJueBPSZI9FoJA +zMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yLS0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHq +ZJx64SIDqZxubw5lT2yHh17zbqD5daWbQOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk52 +7RH89elWsn2/x20Kk4yl0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7I +LaZRfyHBNVOFBkpdn627G190 +-----END CERTIFICATE----- + +USERTrust RSA Certification Authority +===================================== +-----BEGIN CERTIFICATE----- +MIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCBiDELMAkGA1UE +BhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQK +ExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwHhcNMTAwMjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UE +BhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQK +ExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNh +dGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCAEmUXNg7D2wiz +0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2j +Y0K2dvKpOyuR+OJv0OwWIJAJPuLodMkYtJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFn +RghRy4YUVD+8M/5+bJz/Fp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O ++T23LLb2VN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT79uq +/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6c0Plfg6lZrEpfDKE +Y1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmTYo61Zs8liM2EuLE/pDkP2QKe6xJM +lXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97lc6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8 +yexDJtC/QV9AqURE9JnnV4eeUB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+ +eLf8ZxXhyVeEHg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd +BgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF +MAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPFUp/L+M+ZBn8b2kMVn54CVVeW +FPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KOVWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ +7l8wXEskEVX/JJpuXior7gtNn3/3ATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQ +Eg9zKC7F4iRO/Fjs8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM +8WcRiQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYzeSf7dNXGi +FSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZXHlKYC6SQK5MNyosycdi +yA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/qS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9c +J2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRBVXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGw +sAvgnEzDHNb842m1R0aBL6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gx +Q+6IHdfGjjxDah2nGN59PRbxYvnKkKj9 +-----END CERTIFICATE----- + +USERTrust ECC Certification Authority +===================================== +-----BEGIN CERTIFICATE----- +MIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDELMAkGA1UEBhMC +VVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU +aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwHhcNMTAwMjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMC +VVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU +aGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlv +biBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqfloI+d61SRvU8Za2EurxtW2 +0eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinngo4N+LZfQYcTxmdwlkWOrfzCjtHDix6Ez +nPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0GA1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNV +HQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBB +HU6+4WMBzzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbWRNZu +9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg= +-----END CERTIFICATE----- + +GlobalSign ECC Root CA - R4 +=========================== +-----BEGIN CERTIFICATE----- +MIIB4TCCAYegAwIBAgIRKjikHJYKBN5CsiilC+g0mAIwCgYIKoZIzj0EAwIwUDEkMCIGA1UECxMb +R2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI0MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQD +EwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoXDTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMb +R2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI0MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQD +EwpHbG9iYWxTaWduMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuMZ5049sJQ6fLjkZHAOkrprl +OQcJFspjsbmG+IpXwVfOQvpzofdlQv8ewQCybnMO/8ch5RikqtlxP6jUuc6MHaNCMEAwDgYDVR0P +AQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFFSwe61FuOJAf/sKbvu+M8k8o4TV +MAoGCCqGSM49BAMCA0gAMEUCIQDckqGgE6bPA7DmxCGXkPoUVy0D7O48027KqGx2vKLeuwIgJ6iF +JzWbVsaj8kfSt24bAgAXqmemFZHe+pTsewv4n4Q= +-----END CERTIFICATE----- + +GlobalSign ECC Root CA - R5 +=========================== +-----BEGIN CERTIFICATE----- +MIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEkMCIGA1UECxMb +R2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQD +EwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoXDTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMb +R2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQD +EwpHbG9iYWxTaWduMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6 +SFkc8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8kehOvRnkmS +h5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAd +BgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYIKoZIzj0EAwMDaAAwZQIxAOVpEslu28Yx +uglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7 +yFz9SO8NdCKoCOJuxUnOxwy8p2Fp8fc74SrL+SvzZpA3 +-----END CERTIFICATE----- + +Staat der Nederlanden Root CA - G3 +================================== +-----BEGIN CERTIFICATE----- +MIIFdDCCA1ygAwIBAgIEAJiiOTANBgkqhkiG9w0BAQsFADBaMQswCQYDVQQGEwJOTDEeMBwGA1UE +CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSswKQYDVQQDDCJTdGFhdCBkZXIgTmVkZXJsYW5kZW4g +Um9vdCBDQSAtIEczMB4XDTEzMTExNDExMjg0MloXDTI4MTExMzIzMDAwMFowWjELMAkGA1UEBhMC +TkwxHjAcBgNVBAoMFVN0YWF0IGRlciBOZWRlcmxhbmRlbjErMCkGA1UEAwwiU3RhYXQgZGVyIE5l +ZGVybGFuZGVuIFJvb3QgQ0EgLSBHMzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAL4y +olQPcPssXFnrbMSkUeiFKrPMSjTysF/zDsccPVMeiAho2G89rcKezIJnByeHaHE6n3WWIkYFsO2t +x1ueKt6c/DrGlaf1F2cY5y9JCAxcz+bMNO14+1Cx3Gsy8KL+tjzk7FqXxz8ecAgwoNzFs21v0IJy +EavSgWhZghe3eJJg+szeP4TrjTgzkApyI/o1zCZxMdFyKJLZWyNtZrVtB0LrpjPOktvA9mxjeM3K +Tj215VKb8b475lRgsGYeCasH/lSJEULR9yS6YHgamPfJEf0WwTUaVHXvQ9Plrk7O53vDxk5hUUur +mkVLoR9BvUhTFXFkC4az5S6+zqQbwSmEorXLCCN2QyIkHxcE1G6cxvx/K2Ya7Irl1s9N9WMJtxU5 +1nus6+N86U78dULI7ViVDAZCopz35HCz33JvWjdAidiFpNfxC95DGdRKWCyMijmev4SH8RY7Ngzp +07TKbBlBUgmhHbBqv4LvcFEhMtwFdozL92TkA1CvjJFnq8Xy7ljY3r735zHPbMk7ccHViLVlvMDo +FxcHErVc0qsgk7TmgoNwNsXNo42ti+yjwUOH5kPiNL6VizXtBznaqB16nzaeErAMZRKQFWDZJkBE +41ZgpRDUajz9QdwOWke275dhdU/Z/seyHdTtXUmzqWrLZoQT1Vyg3N9udwbRcXXIV2+vD3dbAgMB +AAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRUrfrHkleu +yjWcLhL75LpdINyUVzANBgkqhkiG9w0BAQsFAAOCAgEAMJmdBTLIXg47mAE6iqTnB/d6+Oea31BD +U5cqPco8R5gu4RV78ZLzYdqQJRZlwJ9UXQ4DO1t3ApyEtg2YXzTdO2PCwyiBwpwpLiniyMMB8jPq +KqrMCQj3ZWfGzd/TtiunvczRDnBfuCPRy5FOCvTIeuXZYzbB1N/8Ipf3YF3qKS9Ysr1YvY2WTxB1 +v0h7PVGHoTx0IsL8B3+A3MSs/mrBcDCw6Y5p4ixpgZQJut3+TcCDjJRYwEYgr5wfAvg1VUkvRtTA +8KCWAg8zxXHzniN9lLf9OtMJgwYh/WA9rjLA0u6NpvDntIJ8CsxwyXmA+P5M9zWEGYox+wrZ13+b +8KKaa8MFSu1BYBQw0aoRQm7TIwIEC8Zl3d1Sd9qBa7Ko+gE4uZbqKmxnl4mUnrzhVNXkanjvSr0r +mj1AfsbAddJu+2gw7OyLnflJNZoaLNmzlTnVHpL3prllL+U9bTpITAjc5CgSKL59NVzq4BZ+Extq +1z7XnvwtdbLBFNUjA9tbbws+eC8N3jONFrdI54OagQ97wUNNVQQXOEpR1VmiiXTTn74eS9fGbbeI +JG9gkaSChVtWQbzQRKtqE77RLFi3EjNYsjdj3BP1lB0/QFH1T/U67cjF68IeHRaVesd+QnGTbksV +tzDfqu1XhUisHWrdOWnk4Xl4vs4Fv6EM94B7IWcnMFk= +-----END CERTIFICATE----- + +Staat der Nederlanden EV Root CA +================================ +-----BEGIN CERTIFICATE----- +MIIFcDCCA1igAwIBAgIEAJiWjTANBgkqhkiG9w0BAQsFADBYMQswCQYDVQQGEwJOTDEeMBwGA1UE +CgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSkwJwYDVQQDDCBTdGFhdCBkZXIgTmVkZXJsYW5kZW4g +RVYgUm9vdCBDQTAeFw0xMDEyMDgxMTE5MjlaFw0yMjEyMDgxMTEwMjhaMFgxCzAJBgNVBAYTAk5M +MR4wHAYDVQQKDBVTdGFhdCBkZXIgTmVkZXJsYW5kZW4xKTAnBgNVBAMMIFN0YWF0IGRlciBOZWRl +cmxhbmRlbiBFViBSb290IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA48d+ifkk +SzrSM4M1LGns3Amk41GoJSt5uAg94JG6hIXGhaTK5skuU6TJJB79VWZxXSzFYGgEt9nCUiY4iKTW +O0Cmws0/zZiTs1QUWJZV1VD+hq2kY39ch/aO5ieSZxeSAgMs3NZmdO3dZ//BYY1jTw+bbRcwJu+r +0h8QoPnFfxZpgQNH7R5ojXKhTbImxrpsX23Wr9GxE46prfNeaXUmGD5BKyF/7otdBwadQ8QpCiv8 +Kj6GyzyDOvnJDdrFmeK8eEEzduG/L13lpJhQDBXd4Pqcfzho0LKmeqfRMb1+ilgnQ7O6M5HTp5gV +XJrm0w912fxBmJc+qiXbj5IusHsMX/FjqTf5m3VpTCgmJdrV8hJwRVXj33NeN/UhbJCONVrJ0yPr +08C+eKxCKFhmpUZtcALXEPlLVPxdhkqHz3/KRawRWrUgUY0viEeXOcDPusBCAUCZSCELa6fS/ZbV +0b5GnUngC6agIk440ME8MLxwjyx1zNDFjFE7PZQIZCZhfbnDZY8UnCHQqv0XcgOPvZuM5l5Tnrmd +74K74bzickFbIZTTRTeU0d8JOV3nI6qaHcptqAqGhYqCvkIH1vI4gnPah1vlPNOePqc7nvQDs/nx +fRN0Av+7oeX6AHkcpmZBiFxgV6YuCcS6/ZrPpx9Aw7vMWgpVSzs4dlG4Y4uElBbmVvMCAwEAAaNC +MEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFP6rAJCYniT8qcwa +ivsnuL8wbqg7MA0GCSqGSIb3DQEBCwUAA4ICAQDPdyxuVr5Os7aEAJSrR8kN0nbHhp8dB9O2tLsI +eK9p0gtJ3jPFrK3CiAJ9Brc1AsFgyb/E6JTe1NOpEyVa/m6irn0F3H3zbPB+po3u2dfOWBfoqSmu +c0iH55vKbimhZF8ZE/euBhD/UcabTVUlT5OZEAFTdfETzsemQUHSv4ilf0X8rLiltTMMgsT7B/Zq +5SWEXwbKwYY5EdtYzXc7LMJMD16a4/CrPmEbUCTCwPTxGfARKbalGAKb12NMcIxHowNDXLldRqAN +b/9Zjr7dn3LDWyvfjFvO5QxGbJKyCqNMVEIYFRIYvdr8unRu/8G2oGTYqV9Vrp9canaW2HNnh/tN +f1zuacpzEPuKqf2evTY4SUmH9A4U8OmHuD+nT3pajnnUk+S7aFKErGzp85hwVXIy+TSrK0m1zSBi +5Dp6Z2Orltxtrpfs/J92VoguZs9btsmksNcFuuEnL5O7Jiqik7Ab846+HUCjuTaPPoIaGl6I6lD4 +WeKDRikL40Rc4ZW2aZCaFG+XroHPaO+Zmr615+F/+PoTRxZMzG0IQOeLeG9QgkRQP2YGiqtDhFZK +DyAthg710tvSeopLzaXoTvFeJiUBWSOgftL2fiFX1ye8FVdMpEbB4IMeDExNH08GGeL5qPQ6gqGy +eUN51q1veieQA6TqJIc/2b3Z6fJfUEkc7uzXLg== +-----END CERTIFICATE----- + +IdenTrust Commercial Root CA 1 +============================== +-----BEGIN CERTIFICATE----- +MIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBKMQswCQYDVQQG +EwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBS +b290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQwMTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzES +MBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENB +IDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ld +hNlT3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU+ehcCuz/ +mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gpS0l4PJNgiCL8mdo2yMKi +1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1bVoE/c40yiTcdCMbXTMTEl3EASX2MN0C +XZ/g1Ue9tOsbobtJSdifWwLziuQkkORiT0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl +3ZBWzvurpWCdxJ35UrCLvYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzy +NeVJSQjKVsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZKdHzV +WYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHTc+XvvqDtMwt0viAg +xGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hvl7yTmvmcEpB4eoCHFddydJxVdHix +uuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5NiGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMC +AQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZI +hvcNAQELBQADggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH +6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwtLRvM7Kqas6pg +ghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93nAbowacYXVKV7cndJZ5t+qnt +ozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmV +YjzlVYA211QC//G5Xc7UI2/YRYRKW2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUX +feu+h1sXIFRRk0pTAwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/ro +kTLql1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG4iZZRHUe +2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZmUlO+KWA2yUPHGNiiskz +Z2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7R +cGzM7vRX+Bi6hG6H +-----END CERTIFICATE----- + +IdenTrust Public Sector Root CA 1 +================================= +-----BEGIN CERTIFICATE----- +MIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBNMQswCQYDVQQG +EwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3Rv +ciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcNMzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJV +UzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBS +b290IENBIDEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTy +P4o7ekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGyRBb06tD6 +Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlSbdsHyo+1W/CD80/HLaXI +rcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF/YTLNiCBWS2ab21ISGHKTN9T0a9SvESf +qy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoS +mJxZZoY+rfGwyj4GD3vwEUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFn +ol57plzy9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9VGxyh +LrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ2fjXctscvG29ZV/v +iDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsVWaFHVCkugyhfHMKiq3IXAAaOReyL +4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gDW/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8B +Af8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMw +DQYJKoZIhvcNAQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj +t2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHVDRDtfULAj+7A +mgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9TaDKQGXSc3z1i9kKlT/YPyNt +GtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8GlwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFt +m6/n6J91eEyrRjuazr8FGF1NFTwWmhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMx +NRF4eKLg6TCMf4DfWN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4 +Mhn5+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJtshquDDI +ajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhAGaQdp/lLQzfcaFpPz+vC +ZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ +3Wl9af0AVqW3rLatt8o+Ae+c +-----END CERTIFICATE----- + +Entrust Root Certification Authority - G2 +========================================= +-----BEGIN CERTIFICATE----- +MIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMCVVMxFjAUBgNV +BAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVy +bXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ug +b25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIw +HhcNMDkwNzA3MTcyNTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoT +DUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMx +OTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25s +eTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP +/vaCeb9zYQYKpSfYs1/TRU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXz +HHfV1IWNcCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hWwcKU +s/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1U1+cPvQXLOZprE4y +TGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0jaWvYkxN4FisZDQSA/i2jZRjJKRx +AgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ6 +0B7vfec7aVHUbI2fkBJmqzANBgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5Z +iXMRrEPR9RP/jTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ +Rkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v1fN2D807iDgi +nWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4RnAuknZoh8/CbCzB428Hch0P+ +vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmHVHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xO +e4pIb4tF9g== +-----END CERTIFICATE----- + +Entrust Root Certification Authority - EC1 +========================================== +-----BEGIN CERTIFICATE----- +MIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkGA1UEBhMCVVMx +FjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVn +YWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXpl +ZCB1c2Ugb25seTEzMDEGA1UEAxMqRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5 +IC0gRUMxMB4XDTEyMTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYw +FAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2Fs +LXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQg +dXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAt +IEVDMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHy +AsWfoPZb1YsGGYZPUxBtByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef +9eNi1KlHBz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYE +FLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVCR98crlOZF7ZvHH3h +vxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nXhTcGtXsI/esni0qU+eH6p44mCOh8 +kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G +-----END CERTIFICATE----- + +CFCA EV ROOT +============ +-----BEGIN CERTIFICATE----- +MIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJDTjEwMC4GA1UE +CgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNB +IEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkxMjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEw +MC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQD +DAxDRkNBIEVWIFJPT1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnV +BU03sQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpLTIpTUnrD +7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5/ZOkVIBMUtRSqy5J35DN +uF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp7hZZLDRJGqgG16iI0gNyejLi6mhNbiyW +ZXvKWfry4t3uMCz7zEasxGPrb382KzRzEpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7 +xzbh72fROdOXW3NiGUgthxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9f +py25IGvPa931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqotaK8K +gWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNgTnYGmE69g60dWIol +hdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfVPKPtl8MeNPo4+QgO48BdK4PRVmrJ +tqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hvcWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAf +BgNVHSMEGDAWgBTj/i39KNALtbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB +/wQEAwIBBjAdBgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB +ACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObTej/tUxPQ4i9q +ecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdLjOztUmCypAbqTuv0axn96/Ua +4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBSESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sG +E5uPhnEFtC+NiWYzKXZUmhH4J/qyP5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfX +BDrDMlI1Dlb4pd19xIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjn +aH9dCi77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN5mydLIhy +PDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe/v5WOaHIz16eGWRGENoX +kbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+ZAAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3C +ekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su +-----END CERTIFICATE----- + +OISTE WISeKey Global Root GB CA +=============================== +-----BEGIN CERTIFICATE----- +MIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBtMQswCQYDVQQG +EwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNl +ZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAw +MzJaFw0zOTEyMDExNTEwMzFaMG0xCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYD +VQQLExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEds +b2JhbCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3HEokKtaX +scriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGxWuR51jIjK+FTzJlFXHtP +rby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk +9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNku7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4o +Qnc/nSMbsrY9gBQHTC5P99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvg +GUpuuy9rM2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB +/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUBBAMCAQAwDQYJKoZI +hvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrghcViXfa43FK8+5/ea4n32cZiZBKpD +dHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5gSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0 +VQreUGdNZtGn//3ZwLWoo4rOZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEui +HZeeevJuQHHfaPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic +Nc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM= +-----END CERTIFICATE----- + +SZAFIR ROOT CA2 +=============== +-----BEGIN CERTIFICATE----- +MIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQELBQAwUTELMAkG +A1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6ZW5pb3dhIFMuQS4xGDAWBgNV +BAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkwNzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJ +BgNVBAYTAlBMMSgwJgYDVQQKDB9LcmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYD +VQQDDA9TWkFGSVIgUk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5Q +qEvNQLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT3PSQ1hNK +DJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw3gAeqDRHu5rr/gsUvTaE +2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr63fE9biCloBK0TXC5ztdyO4mTp4CEHCdJ +ckm1/zuVnsHMyAHs6A6KCpbns6aH5db5BSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwi +ieDhZNRnvDF5YTy7ykHNXGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0P +AQH/BAQDAgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsFAAOC +AQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw8PRBEew/R40/cof5 +O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOGnXkZ7/e7DDWQw4rtTw/1zBLZpD67 +oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCPoky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul +4+vJhaAlIDf7js4MNIThPIGyd05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6 ++/NNIxuZMzSgLvWpCz/UXeHPhJ/iGcJfitYgHuNztw== +-----END CERTIFICATE----- + +Certum Trusted Network CA 2 +=========================== +-----BEGIN CERTIFICATE----- +MIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCBgDELMAkGA1UE +BhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMuQS4xJzAlBgNVBAsTHkNlcnR1 +bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIGA1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29y +ayBDQSAyMCIYDzIwMTExMDA2MDgzOTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQ +TDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENl +cnRpZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENB +IDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWADGSdhhuWZGc/IjoedQF9 +7/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+o +CgCXhVqqndwpyeI1B+twTUrWwbNWuKFBOJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40b +Rr5HMNUuctHFY9rnY3lEfktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2p +uTRZCr+ESv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1mo130 +GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02isx7QBlrd9pPPV3WZ +9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOWOZV7bIBaTxNyxtd9KXpEulKkKtVB +Rgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgezTv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pye +hizKV/Ma5ciSixqClnrDvFASadgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vM +BhBgu4M1t15n3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZI +hvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQF/xlhMcQSZDe28cmk4gmb3DW +Al45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTfCVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuA +L55MYIR4PSFk1vtBHxgP58l1cb29XN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMo +clm2q8KMZiYcdywmdjWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tM +pkT/WjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jbAoJnwTnb +w3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksqP/ujmv5zMnHCnsZy4Ypo +J/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Kob7a6bINDd82Kkhehnlt4Fj1F4jNy3eFm +ypnTycUm/Q1oBEauttmbjL4ZvrHG8hnjXALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLX +is7VmFxWlgPF7ncGNf/P5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7 +zAYspsbiDrW5viSP +-----END CERTIFICATE----- + +Hellenic Academic and Research Institutions RootCA 2015 +======================================================= +-----BEGIN CERTIFICATE----- +MIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1IxDzANBgNVBAcT +BkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0 +aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl +YXJjaCBJbnN0aXR1dGlvbnMgUm9vdENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAx +MTIxWjCBpjELMAkGA1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMg +QWNhZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNV +BAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9vdENBIDIw +MTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDC+Kk/G4n8PDwEXT2QNrCROnk8Zlrv +bTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+eh +iGsxr/CL0BgzuNtFajT0AoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+ +6PAQZe104S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06CojXd +FPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV9Cz82XBST3i4vTwr +i5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrDgfgXy5I2XdGj2HUb4Ysn6npIQf1F +GQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6Y5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2 +fu/Z8VFRfS0myGlZYeCsargqNhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9mu +iNX6hME6wGkoLfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc +Bw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNVHRMBAf8EBTAD +AQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVdctA4GGqd83EkVAswDQYJKoZI +hvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0IXtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+ +D1hYc2Ryx+hFjtyp8iY/xnmMsVMIM4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrM +d/K4kPFox/la/vot9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+y +d+2VZ5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/eaj8GsGsVn +82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnhX9izjFk0WaSrT2y7Hxjb +davYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQl033DlZdwJVqwjbDG2jJ9SrcR5q+ss7F +Jej6A7na+RZukYT1HCjI/CbM1xyQVqdfbzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVt +J94Cj8rDtSvK6evIIVM4pcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGa +JI7ZjnHKe7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0vm9q +p/UsQu0yrbYhnr68 +-----END CERTIFICATE----- + +Hellenic Academic and Research Institutions ECC RootCA 2015 +=========================================================== +-----BEGIN CERTIFICATE----- +MIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzANBgNVBAcTBkF0 +aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9u +cyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj +aCBJbnN0aXR1dGlvbnMgRUNDIFJvb3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEw +MzcxMlowgaoxCzAJBgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmlj +IEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5MUQwQgYD +VQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25zIEVDQyBSb290 +Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKgQehLgoRc4vgxEZmGZE4JJS+dQS8KrjVP +dJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJajq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoK +Vlp8aQuqgAkkbH7BRqNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0O +BBYEFLQiC4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaeplSTA +GiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7SofTUwJCA3sS61kFyjn +dc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR +-----END CERTIFICATE----- + +ISRG Root X1 +============ +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UE +BhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQD +EwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQG +EwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMT +DElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54r +Vygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj1 +3Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8K +b4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCN +Aymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ +4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf +1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFu +hjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQH +usEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/r +OPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4G +A1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY +9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV +0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwt +hDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJw +TdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nx +e5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZA +JzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahD +YVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9n +JEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJ +m+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- + +AC RAIZ FNMT-RCM +================ +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsxCzAJBgNVBAYT +AkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBGTk1ULVJDTTAeFw0wODEw +MjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJD +TTEZMBcGA1UECwwQQUMgUkFJWiBGTk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC +ggIBALpxgHpMhm5/yBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcf +qQgfBBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAzWHFctPVr +btQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxFtBDXaEAUwED653cXeuYL +j2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z374jNUUeAlz+taibmSXaXvMiwzn15Cou +08YfxGyqxRxqAQVKL9LFwag0Jl1mpdICIfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mw +WsXmo8RZZUc1g16p6DULmbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnT +tOmlcYF7wk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peSMKGJ +47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2ZSysV4999AeU14EC +ll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMetUqIJ5G+GR4of6ygnXYMgrwTJbFaa +i0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE +FPd9xf3E6Jobd2Sn9R2gzL+HYJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1o +dHRwOi8vd3d3LmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD +nFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1RXxlDPiyN8+s +D8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYMLVN0V2Ue1bLdI4E7pWYjJ2cJ +j+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrT +Qfv6MooqtyuGC2mDOL7Nii4LcK2NJpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW ++YJF1DngoABd15jmfZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7 +Ixjp6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp1txyM/1d +8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B9kiABdcPUXmsEKvU7ANm +5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wokRqEIr9baRRmW1FMdW4R58MD3R++Lj8UG +rp1MYp3/RgT408m2ECVAdf4WqslKYIYvuu8wd+RU4riEmViAqhOLUTpPSPaLtrM= +-----END CERTIFICATE----- + +Amazon Root CA 1 +================ +-----BEGIN CERTIFICATE----- +MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsFADA5MQswCQYD +VQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSAxMB4XDTE1 +MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpv +bjEZMBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBALJ4gHHKeNXjca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgH +FzZM9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qwIFAGbHrQ +gLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6VOujw5H5SNz/0egwLX0t +dHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L93FcXmn/6pUCyziKrlA4b9v7LWIbxcce +VOF34GfID5yHI9Y/QCB/IIDEgEw+OyQmjgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB +/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3 +DQEBCwUAA4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDIU5PM +CCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUsN+gDS63pYaACbvXy +8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vvo/ufQJVtMVT8QtPHRh8jrdkPSHCa +2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2 +xJNDd2ZhwLnoQdeXeGADbkpyrqXRfboQnoZsG4q5WTP468SQvvG5 +-----END CERTIFICATE----- + +Amazon Root CA 2 +================ +-----BEGIN CERTIFICATE----- +MIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwFADA5MQswCQYD +VQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSAyMB4XDTE1 +MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpv +bjEZMBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoC +ggIBAK2Wny2cSkxKgXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4 +kHbZW0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg1dKmSYXp +N+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K8nu+NQWpEjTj82R0Yiw9 +AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvd +fLC6HM783k81ds8P+HgfajZRRidhW+mez/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAEx +kv8LV/SasrlX6avvDXbR8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSS +btqDT6ZjmUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz7Mt0 +Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6+XUyo05f7O0oYtlN +c/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI0u1ufm8/0i2BWSlmy5A5lREedCf+ +3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSw +DPBMMPQFWAJI/TPlUq9LhONmUjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oA +A7CXDpO8Wqj2LIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY ++gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kSk5Nrp+gvU5LE +YFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl7uxMMne0nxrpS10gxdr9HIcW +xkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygmbtmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQ +gj9sAq+uEjonljYE1x2igGOpm/HlurR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbW +aQbLU8uz/mtBzUF+fUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoV +Yh63n749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE76KlXIx3 +KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H9jVlpNMKVv/1F2Rs76gi +JUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT4PsJYGw= +-----END CERTIFICATE----- + +Amazon Root CA 3 +================ +-----BEGIN CERTIFICATE----- +MIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5MQswCQYDVQQG +EwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSAzMB4XDTE1MDUy +NjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZ +MBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZB +f8ANm+gBG1bG8lKlui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjr +Zt6jQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSrttvXBp43 +rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkrBqWTrBqYaGFy+uGh0Psc +eGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteMYyRIHN8wfdVoOw== +-----END CERTIFICATE----- + +Amazon Root CA 4 +================ +-----BEGIN CERTIFICATE----- +MIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5MQswCQYDVQQG +EwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24gUm9vdCBDQSA0MB4XDTE1MDUy +NjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZ +MBcGA1UEAxMQQW1hem9uIFJvb3QgQ0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN +/sGKe0uoe0ZLY7Bi9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri +83BkM6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNV +HQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WBMAoGCCqGSM49BAMDA2gA +MGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlwCkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1 +AE47xDqUEpHJWEadIRNyp4iciuRMStuW1KyLa2tJElMzrdfkviT8tQp21KW8EA== +-----END CERTIFICATE----- + +LuxTrust Global Root 2 +====================== +-----BEGIN CERTIFICATE----- +MIIFwzCCA6ugAwIBAgIUCn6m30tEntpqJIWe5rgV0xZ/u7EwDQYJKoZIhvcNAQELBQAwRjELMAkG +A1UEBhMCTFUxFjAUBgNVBAoMDUx1eFRydXN0IFMuQS4xHzAdBgNVBAMMFkx1eFRydXN0IEdsb2Jh +bCBSb290IDIwHhcNMTUwMzA1MTMyMTU3WhcNMzUwMzA1MTMyMTU3WjBGMQswCQYDVQQGEwJMVTEW +MBQGA1UECgwNTHV4VHJ1c3QgUy5BLjEfMB0GA1UEAwwWTHV4VHJ1c3QgR2xvYmFsIFJvb3QgMjCC +AiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANeFl78RmOnwYoNMPIf5U2o3C/IPPIfOb9wm +Kb3FibrJgz337spbxm1Jc7TJRqMbNBM/wYlFV/TZsfs2ZUv7COJIcRHIbjuend+JZTemhfY7RBi2 +xjcwYkSSl2l9QjAk5A0MiWtj3sXh306pFGxT4GHO9hcvHTy95iJMHZP1EMShduxq3sVs35a0VkBC +wGKSMKEtFZSg0iAGCW5qbeXrt77U8PEVfIvmTroTzEsnXpk8F12PgX8zPU/TPxvsXD/wPEx1bvKm +1Z3aLQdjAsZy6ZS8TEmVT4hSyNvoaYL4zDRbIvCGp4m9SAptZoFtyMhk+wHh9OHe2Z7d21vUKpkm +FRseTJIpgp7VkoGSQXAZ96Tlk0u8d2cx3Rz9MXANF5kM+Qw5GSoXtTBxVdUPrljhPS80m8+f9niF +wpN6cj5mj5wWEWCPnolvZ77gR1o7DJpni89Gxq44o/KnvObWhWszJHAiS8sIm7vI+AIpHb4gDEa/ +a4ebsypmQjVGbKq6rfmYe+lQVRQxv7HaLe2ArWgk+2mr2HETMOZns4dA/Yl+8kPREd8vZS9kzl8U +ubG/Mb2HeFpZZYiq/FkySIbWTLkpS5XTdvN3JW1CHDiDTf2jX5t/Lax5Gw5CMZdjpPuKadUiDTSQ +MC6otOBttpSsvItO13D8xTiOZCXhTTmQzsmHhFhxAgMBAAGjgagwgaUwDwYDVR0TAQH/BAUwAwEB +/zBCBgNVHSAEOzA5MDcGByuBKwEBAQowLDAqBggrBgEFBQcCARYeaHR0cHM6Ly9yZXBvc2l0b3J5 +Lmx1eHRydXN0Lmx1MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBT/GCh2+UgFLKGu8SsbK7JT ++Et8szAdBgNVHQ4EFgQU/xgodvlIBSyhrvErGyuyU/hLfLMwDQYJKoZIhvcNAQELBQADggIBAGoZ +FO1uecEsh9QNcH7X9njJCwROxLHOk3D+sFTAMs2ZMGQXvw/l4jP9BzZAcg4atmpZ1gDlaCDdLnIN +H2pkMSCEfUmmWjfrRcmF9dTHF5kH5ptV5AzoqbTOjFu1EVzPig4N1qx3gf4ynCSecs5U89BvolbW +7MM3LGVYvlcAGvI1+ut7MV3CwRI9loGIlonBWVx65n9wNOeD4rHh4bhY79SV5GCc8JaXcozrhAIu +ZY+kt9J/Z93I055cqqmkoCUUBpvsT34tC38ddfEz2O3OuHVtPlu5mB0xDVbYQw8wkbIEa91WvpWA +VWe+2M2D2RjuLg+GLZKecBPs3lHJQ3gCpU3I+V/EkVhGFndadKpAvAefMLmx9xIX3eP/JEAdemrR +TxgKqpAd60Ae36EeRJIQmvKN4dFLRp7oRUKX6kWZ8+xm1QL68qZKJKrezrnK+T+Tb/mjuuqlPpmt +/f97mfVl7vBZKGfXkJWkE4SphMHozs51k2MavDzq1WQfLSoSOcbDWjLtR5EWDrw4wVDej8oqkDQc +7kGUnF4ZLvhFSZl0kbAEb+MEWrGrKqv+x9CWttrhSmQGbmBNvUJO/3jaJMobtNeWOWyu8Q6qp31I +iyBMz2TWuJdGsE7RKlY6oJO9r4Ak4Ap+58rVyuiFVdw2KuGUaJPHZnJED4AhMmwlxyOAgwrr +-----END CERTIFICATE----- + +TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 +============================================= +-----BEGIN CERTIFICATE----- +MIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIxGDAWBgNVBAcT +D0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxpbXNlbCB2ZSBUZWtub2xvamlr +IEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0wKwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24g +TWVya2V6aSAtIEthbXUgU00xNjA0BgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRp +ZmlrYXNpIC0gU3VydW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYD +VQQGEwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXllIEJpbGlt +c2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklUQUsxLTArBgNVBAsTJEth +bXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBTTTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11 +IFNNIFNTTCBLb2sgU2VydGlmaWthc2kgLSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A +MIIBCgKCAQEAr3UwM6q7a9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y8 +6Ij5iySrLqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INrN3wc +wv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2XYacQuFWQfw4tJzh0 +3+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/iSIzL+aFCr2lqBs23tPcLG07xxO9 +WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4fAJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQU +ZT/HiobGPN08VFw1+DrtUgxHV8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJ +KoZIhvcNAQELBQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh +AHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPfIPP54+M638yc +lNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4lzwDGrpDxpa5RXI4s6ehlj2R +e37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0j +q5Rm+K37DwhuJi1/FwcJsoz7UMCflo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM= +-----END CERTIFICATE----- + +GDCA TrustAUTH R5 ROOT +====================== +-----BEGIN CERTIFICATE----- +MIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UEBhMCQ04xMjAw +BgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8wHQYDVQQD +DBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0MTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVow +YjELMAkGA1UEBhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ +IENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJjDp6L3TQs +AlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBjTnnEt1u9ol2x8kECK62p +OqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+uKU49tm7srsHwJ5uu4/Ts765/94Y9cnrr +pftZTqfrlYwiOXnhLQiPzLyRuEH3FMEjqcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ +9Cy5WmYqsBebnh52nUpmMUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQ +xXABZG12ZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloPzgsM +R6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3GkL30SgLdTMEZeS1SZ +D2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeCjGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4 +oR24qoAATILnsn8JuLwwoC8N9VKejveSswoAHQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx +9hoh49pwBiFYFIeFd3mqgnkCAwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlR +MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg +p8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZmDRd9FBUb1Ov9 +H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5COmSdI31R9KrO9b7eGZONn35 +6ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ryL3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd ++PwyvzeG5LuOmCd+uh8W4XAR8gPfJWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQ +HtZa37dG/OaG+svgIHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBD +F8Io2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV09tL7ECQ +8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQXR4EzzffHqhmsYzmIGrv +/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrqT8p+ck0LcIymSLumoRT2+1hEmRSuqguT +aaApJUqlyyvdimYHFngVV3Eb7PVHhPOeMTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g== +-----END CERTIFICATE----- + +TrustCor RootCert CA-1 +====================== +-----BEGIN CERTIFICATE----- +MIIEMDCCAxigAwIBAgIJANqb7HHzA7AZMA0GCSqGSIb3DQEBCwUAMIGkMQswCQYDVQQGEwJQQTEP +MA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5hbWEgQ2l0eTEkMCIGA1UECgwbVHJ1c3RDb3Ig +U3lzdGVtcyBTLiBkZSBSLkwuMScwJQYDVQQLDB5UcnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3Jp +dHkxHzAdBgNVBAMMFlRydXN0Q29yIFJvb3RDZXJ0IENBLTEwHhcNMTYwMjA0MTIzMjE2WhcNMjkx +MjMxMTcyMzE2WjCBpDELMAkGA1UEBhMCUEExDzANBgNVBAgMBlBhbmFtYTEUMBIGA1UEBwwLUGFu +YW1hIENpdHkxJDAiBgNVBAoMG1RydXN0Q29yIFN5c3RlbXMgUy4gZGUgUi5MLjEnMCUGA1UECwwe +VHJ1c3RDb3IgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MR8wHQYDVQQDDBZUcnVzdENvciBSb290Q2Vy +dCBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv463leLCJhJrMxnHQFgKq1mq +jQCj/IDHUHuO1CAmujIS2CNUSSUQIpidRtLByZ5OGy4sDjjzGiVoHKZaBeYei0i/mJZ0PmnK6bV4 +pQa81QBeCQryJ3pS/C3Vseq0iWEk8xoT26nPUu0MJLq5nux+AHT6k61sKZKuUbS701e/s/OojZz0 +JEsq1pme9J7+wH5COucLlVPat2gOkEz7cD+PSiyU8ybdY2mplNgQTsVHCJCZGxdNuWxu72CVEY4h +gLW9oHPY0LJ3xEXqWib7ZnZ2+AYfYW0PVcWDtxBWcgYHpfOxGgMFZA6dWorWhnAbJN7+KIor0Gqw +/Hqi3LJ5DotlDwIDAQABo2MwYTAdBgNVHQ4EFgQU7mtJPHo/DeOxCbeKyKsZn3MzUOcwHwYDVR0j +BBgwFoAU7mtJPHo/DeOxCbeKyKsZn3MzUOcwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AYYwDQYJKoZIhvcNAQELBQADggEBACUY1JGPE+6PHh0RU9otRCkZoB5rMZ5NDp6tPVxBb5UrJKF5 +mDo4Nvu7Zp5I/5CQ7z3UuJu0h3U/IJvOcs+hVcFNZKIZBqEHMwwLKeXx6quj7LUKdJDHfXLy11yf +ke+Ri7fc7Waiz45mO7yfOgLgJ90WmMCV1Aqk5IGadZQ1nJBfiDcGrVmVCrDRZ9MZyonnMlo2HD6C +qFqTvsbQZJG2z9m2GM/bftJlo6bEjhcxwft+dtvTheNYsnd6djtsL1Ac59v2Z3kf9YKVmgenFK+P +3CghZwnS1k1aHBkcjndcw5QkPTJrS37UeJSDvjdNzl/HHk484IkzlQsPpTLWPFp5LBk= +-----END CERTIFICATE----- + +TrustCor RootCert CA-2 +====================== +-----BEGIN CERTIFICATE----- +MIIGLzCCBBegAwIBAgIIJaHfyjPLWQIwDQYJKoZIhvcNAQELBQAwgaQxCzAJBgNVBAYTAlBBMQ8w +DQYDVQQIDAZQYW5hbWExFDASBgNVBAcMC1BhbmFtYSBDaXR5MSQwIgYDVQQKDBtUcnVzdENvciBT +eXN0ZW1zIFMuIGRlIFIuTC4xJzAlBgNVBAsMHlRydXN0Q29yIENlcnRpZmljYXRlIEF1dGhvcml0 +eTEfMB0GA1UEAwwWVHJ1c3RDb3IgUm9vdENlcnQgQ0EtMjAeFw0xNjAyMDQxMjMyMjNaFw0zNDEy +MzExNzI2MzlaMIGkMQswCQYDVQQGEwJQQTEPMA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5h +bWEgQ2l0eTEkMCIGA1UECgwbVHJ1c3RDb3IgU3lzdGVtcyBTLiBkZSBSLkwuMScwJQYDVQQLDB5U +cnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxHzAdBgNVBAMMFlRydXN0Q29yIFJvb3RDZXJ0 +IENBLTIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCnIG7CKqJiJJWQdsg4foDSq8Gb +ZQWU9MEKENUCrO2fk8eHyLAnK0IMPQo+QVqedd2NyuCb7GgypGmSaIwLgQ5WoD4a3SwlFIIvl9Nk +RvRUqdw6VC0xK5mC8tkq1+9xALgxpL56JAfDQiDyitSSBBtlVkxs1Pu2YVpHI7TYabS3OtB0PAx1 +oYxOdqHp2yqlO/rOsP9+aij9JxzIsekp8VduZLTQwRVtDr4uDkbIXvRR/u8OYzo7cbrPb1nKDOOb +XUm4TOJXsZiKQlecdu/vvdFoqNL0Cbt3Nb4lggjEFixEIFapRBF37120Hapeaz6LMvYHL1cEksr1 +/p3C6eizjkxLAjHZ5DxIgif3GIJ2SDpxsROhOdUuxTTCHWKF3wP+TfSvPd9cW436cOGlfifHhi5q +jxLGhF5DUVCcGZt45vz27Ud+ez1m7xMTiF88oWP7+ayHNZ/zgp6kPwqcMWmLmaSISo5uZk3vFsQP +eSghYA2FFn3XVDjxklb9tTNMg9zXEJ9L/cb4Qr26fHMC4P99zVvh1Kxhe1fVSntb1IVYJ12/+Ctg +rKAmrhQhJ8Z3mjOAPF5GP/fDsaOGM8boXg25NSyqRsGFAnWAoOsk+xWq5Gd/bnc/9ASKL3x74xdh +8N0JqSDIvgmk0H5Ew7IwSjiqqewYmgeCK9u4nBit2uBGF6zPXQIDAQABo2MwYTAdBgNVHQ4EFgQU +2f4hQG6UnrybPZx9mCAZ5YwwYrIwHwYDVR0jBBgwFoAU2f4hQG6UnrybPZx9mCAZ5YwwYrIwDwYD +VR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBAJ5Fngw7tu/h +Osh80QA9z+LqBrWyOrsGS2h60COXdKcs8AjYeVrXWoSK2BKaG9l9XE1wxaX5q+WjiYndAfrs3fnp +kpfbsEZC89NiqpX+MWcUaViQCqoL7jcjx1BRtPV+nuN79+TMQjItSQzL/0kMmx40/W5ulop5A7Zv +2wnL/V9lFDfhOPXzYRZY5LVtDQsEGz9QLX+zx3oaFoBg+Iof6Rsqxvm6ARppv9JYx1RXCI/hOWB3 +S6xZhBqI8d3LT3jX5+EzLfzuQfogsL7L9ziUwOHQhQ+77Sxzq+3+knYaZH9bDTMJBzN7Bj8RpFxw +PIXAz+OQqIN3+tvmxYxoZxBnpVIt8MSZj3+/0WvitUfW2dCFmU2Umw9Lje4AWkcdEQOsQRivh7dv +DDqPys/cA8GiCcjl/YBeyGBCARsaU1q7N6a3vLqE6R5sGtRk2tRD/pOLS/IseRYQ1JMLiI+h2IYU +RpFHmygk71dSTlxCnKr3Sewn6EAes6aJInKc9Q0ztFijMDvd1GpUk74aTfOTlPf8hAs/hCBcNANE +xdqtvArBAs8e5ZTZ845b2EzwnexhF7sUMlQMAimTHpKG9n/v55IFDlndmQguLvqcAFLTxWYp5KeX +RKQOKIETNcX2b2TmQcTVL8w0RSXPQQCWPUouwpaYT05KnJe32x+SMsj/D1Fu1uwJ +-----END CERTIFICATE----- + +TrustCor ECA-1 +============== +-----BEGIN CERTIFICATE----- +MIIEIDCCAwigAwIBAgIJAISCLF8cYtBAMA0GCSqGSIb3DQEBCwUAMIGcMQswCQYDVQQGEwJQQTEP +MA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5hbWEgQ2l0eTEkMCIGA1UECgwbVHJ1c3RDb3Ig +U3lzdGVtcyBTLiBkZSBSLkwuMScwJQYDVQQLDB5UcnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3Jp +dHkxFzAVBgNVBAMMDlRydXN0Q29yIEVDQS0xMB4XDTE2MDIwNDEyMzIzM1oXDTI5MTIzMTE3Mjgw +N1owgZwxCzAJBgNVBAYTAlBBMQ8wDQYDVQQIDAZQYW5hbWExFDASBgNVBAcMC1BhbmFtYSBDaXR5 +MSQwIgYDVQQKDBtUcnVzdENvciBTeXN0ZW1zIFMuIGRlIFIuTC4xJzAlBgNVBAsMHlRydXN0Q29y +IENlcnRpZmljYXRlIEF1dGhvcml0eTEXMBUGA1UEAwwOVHJ1c3RDb3IgRUNBLTEwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDPj+ARtZ+odnbb3w9U73NjKYKtR8aja+3+XzP4Q1HpGjOR +MRegdMTUpwHmspI+ap3tDvl0mEDTPwOABoJA6LHip1GnHYMma6ve+heRK9jGrB6xnhkB1Zem6g23 +xFUfJ3zSCNV2HykVh0A53ThFEXXQmqc04L/NyFIduUd+Dbi7xgz2c1cWWn5DkR9VOsZtRASqnKmc +p0yJF4OuowReUoCLHhIlERnXDH19MURB6tuvsBzvgdAsxZohmz3tQjtQJvLsznFhBmIhVE5/wZ0+ +fyCMgMsq2JdiyIMzkX2woloPV+g7zPIlstR8L+xNxqE6FXrntl019fZISjZFZtS6mFjBAgMBAAGj +YzBhMB0GA1UdDgQWBBREnkj1zG1I1KBLf/5ZJC+Dl5mahjAfBgNVHSMEGDAWgBREnkj1zG1I1KBL +f/5ZJC+Dl5mahjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsF +AAOCAQEABT41XBVwm8nHc2FvcivUwo/yQ10CzsSUuZQRg2dd4mdsdXa/uwyqNsatR5Nj3B5+1t4u +/ukZMjgDfxT2AHMsWbEhBuH7rBiVDKP/mZb3Kyeb1STMHd3BOuCYRLDE5D53sXOpZCz2HAF8P11F +hcCF5yWPldwX8zyfGm6wyuMdKulMY/okYWLW2n62HGz1Ah3UKt1VkOsqEUc8Ll50soIipX1TH0Xs +J5F95yIW6MBoNtjG8U+ARDL54dHRHareqKucBK+tIA5kmE2la8BIWJZpTdwHjFGTot+fDz2LYLSC +jaoITmJF4PkL0uDgPFveXHEnJcLmA4GLEFPjx1WitJ/X5g== +-----END CERTIFICATE----- + +SSL.com Root Certification Authority RSA +======================================== +-----BEGIN CERTIFICATE----- +MIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UEBhMCVVMxDjAM +BgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24x +MTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYw +MjEyMTczOTM5WhcNNDEwMjEyMTczOTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMx +EDAOBgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NM +LmNvbSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2RxFdHaxh3a3by/ZPkPQ/C +Fp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aXqhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8 +P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcCC52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/ge +oeOy3ZExqysdBP+lSgQ36YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkp +k8zruFvh/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrFYD3Z +fBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93EJNyAKoFBbZQ+yODJ +gUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVcUS4cK38acijnALXRdMbX5J+tB5O2 +UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8ZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi8 +1xtZPCvM8hnIk2snYxnP/Okm+Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4s +bE6x/c+cCbqiM+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV +HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4GA1UdDwEB/wQE +AwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGVcpNxJK1ok1iOMq8bs3AD/CUr +dIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBcHadm47GUBwwyOabqG7B52B2ccETjit3E+ZUf +ijhDPwGFpUenPUayvOUiaPd7nNgsPgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAsl +u1OJD7OAUN5F7kR/q5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjq +erQ0cuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jra6x+3uxj +MxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90IH37hVZkLId6Tngr75qNJ +vTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/YK9f1JmzJBjSWFupwWRoyeXkLtoh/D1JI +Pb9s2KJELtFOt3JY04kTlf5Eq/jXixtunLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406y +wKBjYZC6VWg3dGq2ktufoYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NI +WuuA8ShYIc2wBlX7Jz9TkHCpBB5XJ7k= +-----END CERTIFICATE----- + +SSL.com Root Certification Authority ECC +======================================== +-----BEGIN CERTIFICATE----- +MIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMCVVMxDjAMBgNV +BAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24xMTAv +BgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEy +MTgxNDAzWhcNNDEwMjEyMTgxNDAzWjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAO +BgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv +bSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuBBAAiA2IA +BEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI7Z4INcgn64mMU1jrYor+ +8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPgCemB+vNH06NjMGEwHQYDVR0OBBYEFILR +hXMw5zUE044CkvvlpNHEIejNMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTT +jgKS++Wk0cQh6M0wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCW +e+0F+S8Tkdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+gA0z +5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl +-----END CERTIFICATE----- + +SSL.com EV Root Certification Authority RSA R2 +============================================== +-----BEGIN CERTIFICATE----- +MIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNVBAYTAlVTMQ4w +DAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9u +MTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy +MB4XDTE3MDUzMTE4MTQzN1oXDTQyMDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI +DAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYD +VQQDDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMIICIjAN +BgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvqM0fNTPl9fb69LT3w23jh +hqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssufOePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7w +cXHswxzpY6IXFJ3vG2fThVUCAtZJycxa4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTO +Zw+oz12WGQvE43LrrdF9HSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+ +B6KjBSYRaZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcAb9Zh +CBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQGp8hLH94t2S42Oim +9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQVPWKchjgGAGYS5Fl2WlPAApiiECto +RHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMOpgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+Slm +JuwgUHfbSguPvuUCYHBBXtSuUDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48 ++qvWBkofZ6aYMBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV +HSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa49QaAJadz20Zp +qJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBWs47LCp1Jjr+kxJG7ZhcFUZh1 +++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5Sm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nx +Y/hoLVUE0fKNsKTPvDxeH3jnpaAgcLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2G +guDKBAdRUNf/ktUM79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDz +OFSz/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXtll9ldDz7 +CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEmKf7GUmG6sXP/wwyc5Wxq +lD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKKQbNmC1r7fSOl8hqw/96bg5Qu0T/fkreR +rwU7ZcegbLHNYhLDkBvjJc40vG93drEQw/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1 +hlMYegouCRw2n5H9gooiS9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX +9hwJ1C07mKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w== +-----END CERTIFICATE----- + +SSL.com EV Root Certification Authority ECC +=========================================== +-----BEGIN CERTIFICATE----- +MIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMCVVMxDjAMBgNV +BAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9TU0wgQ29ycG9yYXRpb24xNDAy +BgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYw +MjEyMTgxNTIzWhcNNDEwMjEyMTgxNTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMx +EDAOBgNVBAcMB0hvdXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NM +LmNvbSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB +BAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMAVIbc/R/fALhBYlzccBYy +3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1KthkuWnBaBu2+8KGwytAJKaNjMGEwHQYDVR0O +BBYEFFvKXuXe0oGqzagtZFG22XKbl+ZPMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe +5d7SgarNqC1kUbbZcpuX5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJ +N+vp1RPZytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZgh5Mm +m7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg== +-----END CERTIFICATE----- + +GlobalSign Root CA - R6 +======================= +-----BEGIN CERTIFICATE----- +MIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEgMB4GA1UECxMX +R2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkds +b2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQxMjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9i +YWxTaWduIFJvb3QgQ0EgLSBSNjETMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFs +U2lnbjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQss +grRIxutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1kZguSgMpE +3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxDaNc9PIrFsmbVkJq3MQbF +vuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJwLnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqM +PKq0pPbzlUoSB239jLKJz9CgYXfIWHSw1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+ +azayOeSsJDa38O+2HBNXk7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05O +WgtH8wY2SXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/hbguy +CLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4nWUx2OVvq+aWh2IMP +0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpYrZxCRXluDocZXFSxZba/jJvcE+kN +b7gu3GduyYsRtYQUigAZcIN5kZeR1BonvzceMgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQE +AwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNV +HSMEGDAWgBSubAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN +nsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGtIxg93eFyRJa0 +lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr6155wsTLxDKZmOMNOsIeDjHfrY +BzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLjvUYAGm0CuiVdjaExUd1URhxN25mW7xocBFym +Fe944Hn+Xds+qkxV/ZoVqW/hpvvfcDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr +3TsTjxKM4kEaSHpzoHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB1 +0jZpnOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfspA9MRf/T +uTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+vJJUEeKgDu+6B5dpffItK +oZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+t +JDfLRVpOoERIyNiwmcUVhAn21klJwGW45hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA= +-----END CERTIFICATE----- + +OISTE WISeKey Global Root GC CA +=============================== +-----BEGIN CERTIFICATE----- +MIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQswCQYDVQQGEwJD +SDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91bmRhdGlvbiBFbmRvcnNlZDEo +MCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwgUm9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRa +Fw00MjA1MDkwOTU4MzNaMG0xCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQL +ExlPSVNURSBGb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh +bCBSb290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4nieUqjFqdr +VCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4Wp2OQ0jnUsYd4XxiWD1Ab +NTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAd +BgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7TrYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0E +AwMDaAAwZQIwJsdpW9zV57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtk +AjEA2zQgMgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9 +-----END CERTIFICATE----- + +GTS Root R1 +=========== +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQbkepxUtHDA3sM9CJuRz04TANBgkqhkiG9w0BAQwFADBHMQswCQYDVQQG +EwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJv +b3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAG +A1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx +9vaMf/vo27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7wCl7r +aKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjwTcLCeoiKu7rPWRnW +r4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0PfyblqAj+lug8aJRT7oM6iCsVlgmy4HqM +LnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaHszVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly +4cpk9+aCEI3oncKKiPo4Zor8Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr +06zqkUspzBmkMiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92 +wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70paDPvOmbsB4om +3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrNVjzRlwW5y0vtOUucxD/SVRNu +JLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEM +BQADggIBADiWCu49tJYeX++dnAsznyvgyv3SjgofQXSlfKqE1OXyHuY3UjKcC9FhHb8owbZEKTV1 +d5iyfNm9dKyKaOOpMQkpAWBz40d8U6iQSifvS9efk+eCNs6aaAyC58/UEBZvXw6ZXPYfcX3v73sv +fuo21pdwCxXu11xWajOl40k4DLh9+42FpLFZXvRq4d2h9mREruZRgyFmxhE+885H7pwoHyXa/6xm +ld01D1zvICxi/ZG6qcz8WpyTgYMpl0p8WnK0OdC3d8t5/Wk6kjftbjhlRn7pYL15iJdfOBL07q9b +gsiG1eGZbYwE8na6SfZu6W0eX6DvJ4J2QPim01hcDyxC2kLGe4g0x8HYRZvBPsVhHdljUEn2NIVq +4BjFbkerQUIpm/ZgDdIx02OYI5NaAIFItO/Nis3Jz5nu2Z6qNuFoS3FJFDYoOj0dzpqPJeaAcWEr +tXvM+SUWgeExX6GjfhaknBZqlxi9dnKlC54dNuYvoS++cJEPqOba+MSSQGwlfnuzCdyyF62ARPBo +pY+Udf90WuioAnwMCeKpSwughQtiue+hMZL77/ZRBIls6Kl0obsXs7X9SQ98POyDGCBDTtWTurQ0 +sR8WNh8M5mQ5Fkzc4P4dyKliPUDqysU0ArSuiYgzNdwsE3PYJ/HQcu51OyLemGhmW/HGY0dVHLql +CFF1pkgl +-----END CERTIFICATE----- + +GTS Root R2 +=========== +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQbkepxlqz5yDFMJo/aFLybzANBgkqhkiG9w0BAQwFADBHMQswCQYDVQQG +EwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJv +b3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAG +A1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTuk +k3LvCvptnfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY6Dlo +7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAuMC6C/Pq8tBcKSOWI +m8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7kRXuJVfeKH2JShBKzwkCX44ofR5Gm +dFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWgf9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbu +ak7MkogwTZq9TwtImoS1mKPV+3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscsz +cTJGr61K8YzodDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW +Ir9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKaG73Vululycsl +aVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCqgc7dGtxRcw1PcOnlthYhGXmy +5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD +VR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEM +BQADggIBALZp8KZ3/p7uC4Gt4cCpx/k1HUCCq+YEtN/L9x0Pg/B+E02NjO7jMyLDOfxA325BS0JT +vhaI8dI4XsRomRyYUpOM52jtG2pzegVATX9lO9ZY8c6DR2Dj/5epnGB3GFW1fgiTz9D2PGcDFWEJ ++YF59exTpJ/JjwGLc8R3dtyDovUMSRqodt6Sm2T4syzFJ9MHwAiApJiS4wGWAqoC7o87xdFtCjMw +c3i5T1QWvwsHoaRc5svJXISPD+AVdyx+Jn7axEvbpxZ3B7DNdehyQtaVhJ2Gg/LkkM0JR9SLA3Da +WsYDQvTtN6LwG1BUSw7YhN4ZKJmBR64JGz9I0cNv4rBgF/XuIwKl2gBbbZCr7qLpGzvpx0QnRY5r +n/WkhLx3+WuXrD5RRaIRpsyF7gpo8j5QOHokYh4XIDdtak23CZvJ/KRY9bb7nE4Yu5UC56Gtmwfu +Nmsk0jmGwZODUNKBRqhfYlcsu2xkiAhu7xNUX90txGdj08+JN7+dIPT7eoOboB6BAFDC5AwiWVIQ +7UNWhwD4FFKnHYuTjKJNRn8nxnGbJN7k2oaLDX5rIMHAnuFl2GqjpuiFizoHCBy69Y9Vmhh1fuXs +gWbRIXOhNUQLgD1bnF5vKheW0YMjiGZt5obicDIvUiLnyOd/xCxgXS/Dr55FBcOEArf9LAhST4Ld +o/DUhgkC +-----END CERTIFICATE----- + +GTS Root R3 +=========== +-----BEGIN CERTIFICATE----- +MIICDDCCAZGgAwIBAgIQbkepx2ypcyRAiQ8DVd2NHTAKBggqhkjOPQQDAzBHMQswCQYDVQQGEwJV +UzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3Qg +UjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UE +ChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUU +Rout736GjOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL24Cej +QjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTB8Sa6oC2uhYHP +0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEAgFukfCPAlaUs3L6JbyO5o91lAFJekazInXJ0 +glMLfalAvWhgxeG4VDvBNhcl2MG9AjEAnjWSdIUlUfUk7GRSJFClH9voy8l27OyCbvWFGFPouOOa +KaqW04MjyaR7YbPMAuhd +-----END CERTIFICATE----- + +GTS Root R4 +=========== +-----BEGIN CERTIFICATE----- +MIICCjCCAZGgAwIBAgIQbkepyIuUtui7OyrYorLBmTAKBggqhkjOPQQDAzBHMQswCQYDVQQGEwJV +UzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3Qg +UjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UE +ChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcq +hkjOPQIBBgUrgQQAIgNiAATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa +6zzuhXyiQHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvRHYqj +QjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSATNbrdP9JNqPV +2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNnADBkAjBqUFJ0CMRw3J5QdCHojXohw0+WbhXRIjVhLfoI +N+4Zba3bssx9BzT1YBkstTTZbyACMANxsbqjYAuG7ZoIapVon+Kz4ZNkfF6Tpt95LY2F45TPI11x +zPKwTdb+mciUqXWi4w== +-----END CERTIFICATE----- + +UCA Global G2 Root +================== +-----BEGIN CERTIFICATE----- +MIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9MQswCQYDVQQG +EwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBHbG9iYWwgRzIgUm9vdDAeFw0x +NjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0xCzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlU +cnVzdDEbMBkGA1UEAwwSVUNBIEdsb2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A +MIICCgKCAgEAxeYrb3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmT +oni9kmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzmVHqUwCoV +8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/RVogvGjqNO7uCEeBHANBS +h6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDcC/Vkw85DvG1xudLeJ1uK6NjGruFZfc8o +LTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIjtm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/ +R+zvWr9LesGtOxdQXGLYD0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBe +KW4bHAyvj5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6DlNaBa +4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6iIis7nCs+dwp4wwc +OxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznPO6Q0ibd5Ei9Hxeepl2n8pndntd97 +8XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O +BBYEFIHEjMz15DD/pQwIX4wVZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo +5sOASD0Ee/ojL3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5 +1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl1qnN3e92mI0A +Ds0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oUb3n09tDh05S60FdRvScFDcH9 +yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LVPtateJLbXDzz2K36uGt/xDYotgIVilQsnLAX +c47QN6MUPJiVAAwpBVueSUmxX8fjy88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHo +jhJi6IjMtX9Gl8CbEGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZk +bxqgDMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI+Vg7RE+x +ygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGyYiGqhkCyLmTTX8jjfhFn +RR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bXUB+K+wb1whnw0A== +-----END CERTIFICATE----- + +UCA Extended Validation Root +============================ +-----BEGIN CERTIFICATE----- +MIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBHMQswCQYDVQQG +EwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9u +IFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMxMDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8G +A1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIi +MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrs +iWogD4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvSsPGP2KxF +Rv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aopO2z6+I9tTcg1367r3CTu +eUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dksHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR +59mzLC52LqGj3n5qiAno8geK+LLNEOfic0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH +0mK1lTnj8/FtDw5lhIpjVMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KR +el7sFsLzKuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/TuDv +B0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41Gsx2VYVdWf6/wFlth +WG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs1+lvK9JKBZP8nm9rZ/+I8U6laUpS +NwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQDfwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS +3H5aBZ8eNJr34RQwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQEL +BQADggIBADaNl8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR +ap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQVBcZEhrxH9cM +aVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5c6sq1WnIeJEmMX3ixzDx/BR4 +dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb ++7lsq+KePRXBOy5nAliRn+/4Qh8st2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOW +F3sGPjLtx7dCvHaj2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwi +GpWOvpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2CxR9GUeOc +GMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmxcmtpzyKEC2IPrNkZAJSi +djzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbMfjKaiJUINlK73nZfdklJrX+9ZSCyycEr +dhh2n1ax +-----END CERTIFICATE----- + +Certigna Root CA +================ +-----BEGIN CERTIFICATE----- +MIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAwWjELMAkGA1UE +BhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAwMiA0ODE0NjMwODEwMDAzNjEZ +MBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0xMzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjda +MFoxCzAJBgNVBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYz +MDgxMDAwMzYxGTAXBgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sOty3tRQgX +stmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9MCiBtnyN6tMbaLOQdLNyz +KNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPuI9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8 +JXrJhFwLrN1CTivngqIkicuQstDuI7pmTLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16 +XdG+RCYyKfHx9WzMfgIhC59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq +4NYKpkDfePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3YzIoej +wpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWTCo/1VTp2lc5ZmIoJ +lXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1kJWumIWmbat10TWuXekG9qxf5kBdI +jzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5hwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp/ +/TBt2dzhauH8XwIDAQABo4IBGjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYw +HQYDVR0OBBYEFBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of +1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczovL3d3d3cuY2Vy +dGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilodHRwOi8vY3JsLmNlcnRpZ25h +LmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYraHR0cDovL2NybC5kaGlteW90aXMuY29tL2Nl +cnRpZ25hcm9vdGNhLmNybDANBgkqhkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOIt +OoldaDgvUSILSo3L6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxP +TGRGHVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH60BGM+RFq +7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncBlA2c5uk5jR+mUYyZDDl3 +4bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdio2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd +8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1gPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS +6Cvu5zHbugRqh5jnxV/vfaci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaY +tlu3zM63Nwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayhjWZS +aX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw3kAP+HwV96LOPNde +E4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0= +-----END CERTIFICATE----- + +emSign Root CA - G1 +=================== +-----BEGIN CERTIFICATE----- +MIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYDVQQGEwJJTjET +MBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRl +ZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBHMTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgx +ODMwMDBaMGcxCzAJBgNVBAYTAklOMRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVk +aHJhIFRlY2hub2xvZ2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQzf2N4aLTN +LnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO8oG0x5ZOrRkVUkr+PHB1 +cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aqd7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHW +DV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhMtTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ +6DqS0hdW5TUaQBw+jSztOd9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrH +hQIDAQABo0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQDAgEG +MA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31xPaOfG1vR2vjTnGs2 +vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjMwiI/aTvFthUvozXGaCocV685743Q +NcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6dGNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q ++Mri/Tm3R7nrft8EI6/6nAYH6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeih +U80Bv2noWgbyRQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx +iN66zB+Afko= +-----END CERTIFICATE----- + +emSign ECC Root CA - G3 +======================= +-----BEGIN CERTIFICATE----- +MIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQGEwJJTjETMBEG +A1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEg +MB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4 +MTgzMDAwWjBrMQswCQYDVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11 +ZGhyYSBUZWNobm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g +RzMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0WXTsuwYc +58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xySfvalY8L1X44uT6EYGQIr +MgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuBzhccLikenEhjQjAOBgNVHQ8BAf8EBAMC +AQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+D +CBeQyh+KTOgNG3qxrdWBCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7 +jHvrZQnD+JbNR6iC8hZVdyR+EhCVBCyj +-----END CERTIFICATE----- + +emSign Root CA - C1 +=================== +-----BEGIN CERTIFICATE----- +MIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkGA1UEBhMCVVMx +EzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNp +Z24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAwMFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UE +BhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQD +ExNlbVNpZ24gUm9vdCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+up +ufGZBczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZHdPIWoU/ +Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH3DspVpNqs8FqOp099cGX +OFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvHGPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4V +I5b2P/AgNBbeCsbEBEV5f6f9vtKppa+cxSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleooms +lMuoaJuvimUnzYnu3Yy1aylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+ +XJGFehiqTbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQAD +ggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87/kOXSTKZEhVb3xEp +/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4kqNPEjE2NuLe/gDEo2APJ62gsIq1 +NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrGYQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9 +wC68AivTxEDkigcxHpvOJpkT+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQ +BmIMMMAVSKeoWXzhriKi4gp6D/piq1JM4fHfyr6DDUI= +-----END CERTIFICATE----- + +emSign ECC Root CA - C3 +======================= +-----BEGIN CERTIFICATE----- +MIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQGEwJVUzETMBEG +A1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMxIDAeBgNVBAMTF2VtU2lnbiBF +Q0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAwMFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UE +BhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQD +ExdlbVNpZ24gRUNDIFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd +6bciMK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4OjavtisIGJAnB9 +SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0OBBYEFPtaSNCAIEDyqOkA +B2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMDA2gA +MGUCMQC02C8Cif22TGK6Q04ThHK1rt0c3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwU +ZOR8loMRnLDRWmFLpg9J0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ== +-----END CERTIFICATE----- + +Hongkong Post Root CA 3 +======================= +-----BEGIN CERTIFICATE----- +MIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQELBQAwbzELMAkG +A1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJSG9uZyBLb25nMRYwFAYDVQQK +Ew1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25na29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2 +MDMwMjI5NDZaFw00MjA2MDMwMjI5NDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtv +bmcxEjAQBgNVBAcTCUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMX +SG9uZ2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz +iNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFOdem1p+/l6TWZ5Mwc50tf +jTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mIVoBc+L0sPOFMV4i707mV78vH9toxdCim +5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOe +sL4jpNrcyCse2m5FHomY2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj +0mRiikKYvLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+TtbNe/ +JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZbx39ri1UbSsUgYT2u +y1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+l2oBlKN8W4UdKjk60FSh0Tlxnf0h ++bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YKTE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsG +xVd7GYYKecsAyVKvQv83j+GjHno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwID +AQABo2MwYTAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e +i9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEwDQYJKoZIhvcN +AQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG7BJ8dNVI0lkUmcDrudHr9Egw +W62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCkMpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWld +y8joRTnU+kLBEUx3XZL7av9YROXrgZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov ++BS5gLNdTaqX4fnkGMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDc +eqFS3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJmOzj/2ZQw +9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+l6mc1X5VTMbeRRAc6uk7 +nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6cJfTzPV4e0hz5sy229zdcxsshTrD3mUcY +hcErulWuBurQB7Lcq9CClnXO0lD+mefPL5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB +60PZ2Pierc+xYw5F9KBaLJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fq +dBb9HxEGmpv0 +-----END CERTIFICATE----- diff --git a/external/libhv/libhv-1.3.2/cert/gen.sh b/external/libhv/libhv-1.3.2/cert/gen.sh new file mode 100644 index 0000000..f9f6ff4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cert/gen.sh @@ -0,0 +1,2 @@ +openssl genrsa -out server.key 2048 +openssl req -new -x509 -key server.key -out server.crt -days 3650 diff --git a/external/libhv/libhv-1.3.2/cert/server.crt b/external/libhv/libhv-1.3.2/cert/server.crt new file mode 100644 index 0000000..93c2a91 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cert/server.crt @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDgjCCAmqgAwIBAgIJAL/XKTs4cCwRMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV +BAYTAkNOMREwDwYDVQQIDAhTaGFuZ2hhaTERMA8GA1UEBwwIU2hhbmdoYWkxITAf +BgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0xOTA4MjkwNDA1NDda +Fw0yOTA4MjYwNDA1NDdaMFYxCzAJBgNVBAYTAkNOMREwDwYDVQQIDAhTaGFuZ2hh +aTERMA8GA1UEBwwIU2hhbmdoYWkxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMg +UHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANJJ5DaZroEg +N34H6A3uq5qDRlJe/ELhWcmtkj57cYb5U/T39C7dEjqGfhURb/NEuYbYoEb+4/lD +xJOvn0qqXiJGPt0avecGhQUpggykEj4NZe6W1/WIX81Z1tF6QJZrpUDq4MD1S3KA +ETvnTDv0bc6lvT/YDDb8qYMKGNZUTIQKpucdrIet9kDVIrXON4icJL9PDi/zFu3S +e6feGsG7SAWv1ZInzF6wkEr8pCQc2Aab9R2BsbDsnVc8qZahfLniif7yDxiRbcEf +P4P4cJ7YCD6T1Vyv7bDCnxSEJ+b+j4Ih5XVwHUeK2wG9rrNQ6Z4sSMrv1oSoxVfG +mGdHHEhBN0ECAwEAAaNTMFEwHQYDVR0OBBYEFGPOMSeA6p3Vkf4uHdt5eRbrkoXU +MB8GA1UdIwQYMBaAFGPOMSeA6p3Vkf4uHdt5eRbrkoXUMA8GA1UdEwEB/wQFMAMB +Af8wDQYJKoZIhvcNAQELBQADggEBAEa3x7MzIBQvr43l6zuoK9SBoW6DET42yCRb +YA6as/8fFYc4A1GqJStjvOgS0nIhBeCdyLJCy40U5ERhhVKqjPLLHHB4i7sv98Ac +aXgVr91eUZcKeuiEkDHWRPCitkPj3p2v9J2VDAHpxfKvIB+r/q+7O4W6tjJT5fPq +iUgdpr/R6uBFndBtGc+k65byxSQgvAvdM4kpGA8nnypT9i8SGVp0gB7lMG8avUTU +zH16msecIEKLBHED40w9aiuOf3CnMDqGSTilP7p4gvMY4u+qm3zAXN29OHqoldbn +j/A8RE9Q1F1H3G+eSltBuug3DBGp0q0EskxiqtfJbzW9G5fwGxM= +-----END CERTIFICATE----- diff --git a/external/libhv/libhv-1.3.2/cert/server.key b/external/libhv/libhv-1.3.2/cert/server.key new file mode 100644 index 0000000..144266e --- /dev/null +++ b/external/libhv/libhv-1.3.2/cert/server.key @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEA0knkNpmugSA3fgfoDe6rmoNGUl78QuFZya2SPntxhvlT9Pf0 +Lt0SOoZ+FRFv80S5htigRv7j+UPEk6+fSqpeIkY+3Rq95waFBSmCDKQSPg1l7pbX +9YhfzVnW0XpAlmulQOrgwPVLcoARO+dMO/RtzqW9P9gMNvypgwoY1lRMhAqm5x2s +h632QNUitc43iJwkv08OL/MW7dJ7p94awbtIBa/VkifMXrCQSvykJBzYBpv1HYGx +sOydVzyplqF8ueKJ/vIPGJFtwR8/g/hwntgIPpPVXK/tsMKfFIQn5v6PgiHldXAd +R4rbAb2us1DpnixIyu/WhKjFV8aYZ0ccSEE3QQIDAQABAoIBAG/JthbMdbbRAI7v +9w1I/lKCTKTHN8T59PhAXAj5KG2/J0GHenhbLzCLhIUAowmoVBP6HqH/KAO/YcW8 +y6oujSIdQ5fYenFQxu/qk+bSZZw1FSXTbHRrDbqlcowjOCh+ivfKpLYO8A+rQv4c +RCtvEdyTwNoqqLumbxppCLEPWSmrZOuw/EegeDMRspMpPNsFsk7mcl2w3jJjiX9D +NB/yHZZzbZoTf/ayT/ca6FueKqPF52jIiuDzOncE1PqQ8hiPrXFIh4yZYCn1IpnK +48hotm3NSixpnag6UziwCRSoPsUCue8h2h3Tr690Lr/7LzILdtBJ+4Qxs3mU8Crz ++bM7Xo0CgYEA9K94Gp0gyIxEiIPQ/zcOLeY2y3gUpS5LNaM6lxm82u4nsrC4FQJZ +H72kV6YxvedmC1JZcYc6WiaAelkv9GqSekTMFv05rTsA4zQX59habsXPa5r3vzds +NzgdjhDfwvWZCp3QXDG1n0wEMKJleG9+CK7khQ4doHmjQtCt0w16AxMCgYEA3AM9 +qxJSOADePq0G4fJ+4jAr4MgsMBsWaGEWU0Z7pBaTj+hm0ULiwShWy9/bbxw+zZgL +VqE0cCiqKsMZMFtZvwX89fIN71YLkyTbl5Y/Lb65HKfKI8a8LGSNNaAd6CG9vy2C +krqDKoHILCQdBpT7tSi2vF57+uDxJDH6+VyZ0tsCgYEAsVE7o2W87TihLaEA4wJ9 +1wtfKCJUK8QZorwwaHGxZ6JwyFDChg8WkSb4IsCAiZNYYtoBkYEi61O9hWx+kQxu +LAcRM5O8qWn54azNqikil+Xnw54g7cR3OqkC2gImdf1PM99bsIQhj1giLTBygk2h +sx8y4a1yEOo1QuVBIpJAmlsCgYEAv3NehXAC9dLjkny0oYeIHEG43PizYwUfQaNC +byLFUquGqtKcLfrbISR+KxjYdV6J1BQ7wZ2z6Omp8l4lnCvR8+U9E7QXpi4lEl0f +bVCEF8WAhcwInYtBkgvJyWFUxPwfhq4OkqoUm7elvauLSn/4bNNJ+K7riguWK14G +vFl1TcMCgYEA9EDTbpBl1oXICe2xevuh1HJQ1eBXAXP0l3hy0h76czBoBlnoF13A +6TOy6iSE3tpEwGPZZ33goKZdKyBLXG3TmemthWMxjBHc31C55gpIIgYPlW4Blv35 +djt8AlxF68VKIhY7CkaGhNmUpdSSfANHyirfw9rx70IRwRJfnZ5MN+M= +-----END RSA PRIVATE KEY----- diff --git a/external/libhv/libhv-1.3.2/cmake/ios.toolchain.cmake b/external/libhv/libhv-1.3.2/cmake/ios.toolchain.cmake new file mode 100644 index 0000000..8f3d814 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cmake/ios.toolchain.cmake @@ -0,0 +1,1028 @@ +# This file is part of the ios-cmake project. It was retrieved from +# https://github.com/leetal/ios-cmake.git, which is a fork of +# https://github.com/gerstrong/ios-cmake.git, which is a fork of +# https://github.com/cristeab/ios-cmake.git, which is a fork of +# https://code.google.com/p/ios-cmake/. Which in turn is based off of +# the Platform/Darwin.cmake and Platform/UnixPaths.cmake files which +# are included with CMake 2.8.4 +# +# The ios-cmake project is licensed under the new BSD license. +# +# Copyright (c) 2014, Bogdan Cristea and LTE Engineering Software, +# Kitware, Inc., Insight Software Consortium. 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. +# +# 3. Neither the name of the 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 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 HOLDER 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. +# +# This file is based on the Platform/Darwin.cmake and +# Platform/UnixPaths.cmake files which are included with CMake 2.8.4 +# It has been altered for iOS development. +# +# Updated by Alex Stewart (alexs.mac@gmail.com) +# +# ***************************************************************************** +# Now maintained by Alexander Widerberg (widerbergaren [at] gmail.com) +# under the BSD-3-Clause license +# https://github.com/leetal/ios-cmake +# ***************************************************************************** +# +# INFORMATION / HELP +# +############################################################################### +# OPTIONS # +############################################################################### +# +# PLATFORM: (default "OS64") +# OS = Build for iPhoneOS. +# OS64 = Build for arm64 iphoneOS. +# OS64COMBINED = Build for arm64 x86_64 iphoneOS + iphoneOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) +# SIMULATOR = Build for x86 i386 iphoneOS Simulator. +# SIMULATOR64 = Build for x86_64 iphoneOS Simulator. +# SIMULATORARM64 = Build for arm64 iphoneOS Simulator. +# TVOS = Build for arm64 tvOS. +# TVOSCOMBINED = Build for arm64 x86_64 tvOS + tvOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) +# SIMULATOR_TVOS = Build for x86_64 tvOS Simulator. +# WATCHOS = Build for armv7k arm64_32 for watchOS. +# WATCHOSCOMBINED = Build for armv7k arm64_32 x86_64 watchOS + watchOS Simulator. Combined into FAT STATIC lib (only supported on 3.14+ of CMake with "-G Xcode" argument in combination with the "cmake --install" CMake build step) +# SIMULATOR_WATCHOS = Build for x86_64 for watchOS Simulator. +# MAC = Build for x86_64 macOS. +# MAC_ARM64 = Build for Apple Silicon macOS. +# MAC_UNIVERSAL = Combined build for x86_64 and Apple Silicon on macOS. +# MAC_CATALYST = Build for x86_64 macOS with Catalyst support (iOS toolchain on macOS). +# Note: The build argument "MACOSX_DEPLOYMENT_TARGET" can be used to control min-version of macOS +# MAC_CATALYST_ARM64 = Build for Apple Silicon macOS with Catalyst support (iOS toolchain on macOS). +# Note: The build argument "MACOSX_DEPLOYMENT_TARGET" can be used to control min-version of macOS +# +# CMAKE_OSX_SYSROOT: Path to the SDK to use. By default this is +# automatically determined from PLATFORM and xcodebuild, but +# can also be manually specified (although this should not be required). +# +# CMAKE_DEVELOPER_ROOT: Path to the Developer directory for the platform +# being compiled for. By default, this is automatically determined from +# CMAKE_OSX_SYSROOT, but can also be manually specified (although this should +# not be required). +# +# DEPLOYMENT_TARGET: Minimum SDK version to target. Default 2.0 on watchOS and 9.0 on tvOS+iOS +# +# NAMED_LANGUAGE_SUPPORT: +# ON (default) = Will require "enable_language(OBJC) and/or enable_language(OBJCXX)" for full OBJC|OBJCXX support +# OFF = Will embed the OBJC and OBJCXX flags into the CMAKE_C_FLAGS and CMAKE_CXX_FLAGS (legacy behavior, CMake version < 3.16) +# +# ENABLE_BITCODE: (ON|OFF) Enables or disables bitcode support. Default ON +# +# ENABLE_ARC: (ON|OFF) Enables or disables ARC support. Default ON (ARC enabled by default) +# +# ENABLE_VISIBILITY: (ON|OFF) Enables or disables symbol visibility support. Default OFF (visibility hidden by default) +# +# ENABLE_STRICT_TRY_COMPILE: (ON|OFF) Enables or disables strict try_compile() on all Check* directives (will run linker +# to actually check if linking is possible). Default OFF (will set CMAKE_TRY_COMPILE_TARGET_TYPE to STATIC_LIBRARY) +# +# ARCHS: (armv7 armv7s armv7k arm64 arm64_32 i386 x86_64) If specified, will override the default architectures for the given PLATFORM +# OS = armv7 armv7s arm64 (if applicable) +# OS64 = arm64 (if applicable) +# SIMULATOR = i386 +# SIMULATOR64 = x86_64 +# SIMULATORARM64 = arm64 +# TVOS = arm64 +# SIMULATOR_TVOS = x86_64 (i386 has since long been deprecated) +# WATCHOS = armv7k arm64_32 (if applicable) +# SIMULATOR_WATCHOS = x86_64 (i386 has since long been deprecated) +# MAC = x86_64 +# MAC_ARM64 = arm64 +# MAC_UNIVERSAL = x86_64 arm64 +# MAC_CATALYST = x86_64 +# MAC_CATALYST_ARM64 = arm64 +# +# NOTE: When manually specifying ARCHS, put a semi-colon between the entries. E.g., -DARCHS="armv7;arm64" +# +############################################################################### +# END OPTIONS # +############################################################################### +# +# This toolchain defines the following properties (available via get_property()) for use externally: +# +# PLATFORM: The currently targeted platform. +# XCODE_VERSION: Version number (not including Build version) of Xcode detected. +# SDK_VERSION: Version of SDK being used. +# OSX_ARCHITECTURES: Architectures being compiled for (generated from PLATFORM). +# APPLE_TARGET_TRIPLE: Used by autoconf build systems. NOTE: If "ARCHS" is overridden, this will *NOT* be set! +# +# This toolchain defines the following macros for use externally: +# +# set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE XCODE_VARIANT) +# A convenience macro for setting xcode specific properties on targets. +# Available variants are: All, Release, RelWithDebInfo, Debug, MinSizeRel +# example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1" "all"). +# +# find_host_package (PROGRAM ARGS) +# A macro used to find executable programs on the host system, not within the +# environment. Thanks to the android-cmake project for providing the +# command. +# + +cmake_minimum_required(VERSION 3.8.0) + +# CMake invokes the toolchain file twice during the first build, but only once during subsequent rebuilds. +if(DEFINED ENV{_IOS_TOOLCHAIN_HAS_RUN}) + return() +endif() +set(ENV{_IOS_TOOLCHAIN_HAS_RUN} true) + +# List of supported platform values +list(APPEND _supported_platforms + "OS" "OS64" "OS64COMBINED" "SIMULATOR" "SIMULATOR64" "SIMULATORARM64" + "TVOS" "TVOSCOMBINED" "SIMULATOR_TVOS" + "WATCHOS" "WATCHOSCOMBINED" "SIMULATOR_WATCHOS" + "MAC" "MAC_ARM64" "MAC_UNIVERSAL" + "MAC_CATALYST" "MAC_CATALYST_ARM64") + +# Cache what generator is used +set(USED_CMAKE_GENERATOR "${CMAKE_GENERATOR}") + +# Check if using a CMake version capable of building combined FAT builds (simulator and target slices combined in one static lib) +if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14") + set(MODERN_CMAKE YES) +endif() + +# Get the Xcode version being used. +# Problem: CMake runs toolchain files multiple times, but can't read cache variables on some runs. +# Workaround: On the first run (in which cache variables are always accessible), set an intermediary environment variable. +# +# NOTE: This pattern is used in many places in this toolchain to speed up checks of all sorts +if(DEFINED XCODE_VERSION_INT) + # Environment variables are always preserved. + set(ENV{_XCODE_VERSION_INT} "${XCODE_VERSION_INT}") +elseif(DEFINED ENV{_XCODE_VERSION_INT}) + set(XCODE_VERSION_INT "$ENV{_XCODE_VERSION_INT}") +elseif(NOT DEFINED XCODE_VERSION_INT) + find_program(XCODEBUILD_EXECUTABLE xcodebuild) + if(NOT XCODEBUILD_EXECUTABLE) + message(FATAL_ERROR "xcodebuild not found. Please install either the standalone commandline tools or Xcode.") + endif() + execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -version + OUTPUT_VARIABLE XCODE_VERSION_INT + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + string(REGEX MATCH "Xcode [0-9\\.]+" XCODE_VERSION_INT "${XCODE_VERSION_INT}") + string(REGEX REPLACE "Xcode ([0-9\\.]+)" "\\1" XCODE_VERSION_INT "${XCODE_VERSION_INT}") + set(XCODE_VERSION_INT "${XCODE_VERSION_INT}" CACHE INTERNAL "") +endif() + +# Assuming that xcode 12.0 is installed you most probably have ios sdk 14.0 or later installed (tested on Big Sur) +# if you don't set a deployment target it will be set the way you only get 64-bit builds +if(NOT DEFINED DEPLOYMENT_TARGET AND XCODE_VERSION_INT VERSION_GREATER 12.0) + # Temporarily fix the arm64 issues in CMake install-combined by excluding arm64 for simulator builds (needed for Apple Silicon...) + set(CMAKE_XCODE_ATTRIBUTE_EXCLUDED_ARCHS[sdk=iphonesimulator*] "arm64") +endif() + +# Check if the platform variable is set +if(DEFINED PLATFORM) + # Environment variables are always preserved. + set(ENV{_PLATFORM} "${PLATFORM}") +elseif(DEFINED ENV{_PLATFORM}) + set(PLATFORM "$ENV{_PLATFORM}") +elseif(NOT DEFINED PLATFORM) + message(FATAL_ERROR "PLATFORM argument not set. Bailing configure since I don't know what target you want to build for!") +endif () + +if(PLATFORM MATCHES ".*COMBINED" AND NOT CMAKE_GENERATOR MATCHES "Xcode") + message(FATAL_ERROR "The combined builds support requires Xcode to be used as a generator via '-G Xcode' command-line argument in CMake") +endif() + +# Safeguard that the platform value is set and is one of the supported values +list(FIND _supported_platforms ${PLATFORM} contains_PLATFORM) +if("${contains_PLATFORM}" EQUAL "-1") + string(REPLACE ";" "\n * " _supported_platforms_formatted "${_supported_platforms}") + message(FATAL_ERROR " Invalid PLATFORM specified! Current value: ${PLATFORM}.\n" + " Supported PLATFORM values: \n * ${_supported_platforms_formatted}") +endif() + +# Check if Apple Silicon is supported +if(PLATFORM MATCHES "^(MAC_ARM64)$|^(MAC_CATALYST_ARM64)$|^(MAC_UNIVERSAL)$" AND ${CMAKE_VERSION} VERSION_LESS "3.19.5") + message(FATAL_ERROR "Apple Silicon builds requires a minimum of CMake 3.19.5") +endif() + +# Touch the toolchain variable to suppress the "unused variable" warning. +# This happens if CMake is invoked with the same command line the second time. +if(CMAKE_TOOLCHAIN_FILE) +endif() + +# Fix for PThread library not in path +set(CMAKE_THREAD_LIBS_INIT "-lpthread") +set(CMAKE_HAVE_THREADS_LIBRARY 1) +set(CMAKE_USE_WIN32_THREADS_INIT 0) +set(CMAKE_USE_PTHREADS_INIT 1) + +# Specify named language support defaults. +if(NOT DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.16") + set(NAMED_LANGUAGE_SUPPORT ON) + message(STATUS "[DEFAULTS] Using explicit named language support! E.g., enable_language(CXX) is needed in the project files.") +elseif(NOT DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_LESS "3.16") + set(NAMED_LANGUAGE_SUPPORT OFF) + message(STATUS "[DEFAULTS] Disabling explicit named language support. Falling back to legacy behavior.") +elseif(DEFINED NAMED_LANGUAGE_SUPPORT AND ${CMAKE_VERSION} VERSION_LESS "3.16") + message(FATAL_ERROR "CMake named language support for OBJC and OBJCXX was added in CMake 3.16.") +endif() +set(NAMED_LANGUAGE_SUPPORT_INT ${NAMED_LANGUAGE_SUPPORT} CACHE BOOL + "Whether or not to enable explicit named language support" FORCE) + +# Specify the minimum version of the deployment target. +if(NOT DEFINED DEPLOYMENT_TARGET) + if (PLATFORM MATCHES "WATCHOS") + # Unless specified, SDK version 4.0 is used by default as minimum target version (watchOS). + set(DEPLOYMENT_TARGET "4.0") + elseif(PLATFORM STREQUAL "MAC") + # Unless specified, SDK version 10.13 (High Sierra) is used by default as the minimum target version (macos). + set(DEPLOYMENT_TARGET "10.13") + elseif(PLATFORM STREQUAL "MAC_ARM64") + # Unless specified, SDK version 11.0 (Big Sur) is used by default as the minimum target version (macOS on arm). + set(DEPLOYMENT_TARGET "11.0") + elseif(PLATFORM STREQUAL "MAC_UNIVERSAL") + # Unless specified, SDK version 11.0 (Big Sur) is used by default as minimum target version for universal builds. + set(DEPLOYMENT_TARGET "11.0") + elseif(PLATFORM STREQUAL "MAC_CATALYST" OR PLATFORM STREQUAL "MAC_CATALYST_ARM64") + # Unless specified, SDK version 13.0 is used by default as the minimum target version (mac catalyst minimum requirement). + set(DEPLOYMENT_TARGET "13.1") + else() + # Unless specified, SDK version 11.0 is used by default as the minimum target version (iOS, tvOS). + set(DEPLOYMENT_TARGET "11.0") + endif() + message(STATUS "[DEFAULTS] Using the default min-version since DEPLOYMENT_TARGET not provided!") +elseif(DEFINED DEPLOYMENT_TARGET AND PLATFORM MATCHES "^MAC_CATALYST" AND ${DEPLOYMENT_TARGET} VERSION_LESS "13.1") + message(FATAL_ERROR "Mac Catalyst builds requires a minimum deployment target of 13.1!") +endif() + +# Store the DEPLOYMENT_TARGET in the cache +set(DEPLOYMENT_TARGET "${DEPLOYMENT_TARGET}" CACHE INTERNAL "") + +# Handle the case where we are targeting iOS and a version above 10.3.4 (32-bit support dropped officially) +if(PLATFORM STREQUAL "OS" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) + set(PLATFORM "OS64") + message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") +elseif(PLATFORM STREQUAL "SIMULATOR" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) + set(PLATFORM "SIMULATOR64") + message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") +endif() + +set(PLATFORM_INT "${PLATFORM}") + +if(DEFINED ARCHS) + string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") +endif() + +# Determine the platform name and architectures for use in xcodebuild commands +# from the specified PLATFORM_INT name. +if(PLATFORM_INT STREQUAL "OS") + set(SDK_NAME iphoneos) + if(NOT ARCHS) + set(ARCHS armv7 armv7s arm64) + set(APPLE_TARGET_TRIPLE_INT arm-apple-ios${DEPLOYMENT_TARGET}) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) + endif() +elseif(PLATFORM_INT STREQUAL "OS64") + set(SDK_NAME iphoneos) + if(NOT ARCHS) + if (XCODE_VERSION_INT VERSION_GREATER 10.0) + set(ARCHS arm64) # FIXME: Add arm64e when Apple has fixed the integration issues with it, libarclite_iphoneos.a is currently missing bitcode markers for example + else() + set(ARCHS arm64) + endif() + set(APPLE_TARGET_TRIPLE_INT aarch64-apple-ios${DEPLOYMENT_TARGET}) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) + endif() +elseif(PLATFORM_INT STREQUAL "OS64COMBINED") + set(SDK_NAME iphoneos) + if(MODERN_CMAKE) + if(NOT ARCHS) + if (XCODE_VERSION_INT VERSION_GREATER 10.0) + set(ARCHS arm64 x86_64) # FIXME: Add arm64e when Apple has fixed the integration issues with it, libarclite_iphoneos.a is currently missing bitcode markers for example + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphoneos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphonesimulator*] "x86_64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphoneos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphonesimulator*] "x86_64") + else() + set(ARCHS arm64 x86_64) + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphoneos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=iphonesimulator*] "x86_64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphoneos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=iphonesimulator*] "x86_64") + endif() + set(APPLE_TARGET_TRIPLE_INT aarch64-x86_64-apple-ios${DEPLOYMENT_TARGET}) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}) + endif() + else() + message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the OS64COMBINED setting work") + endif() +elseif(PLATFORM_INT STREQUAL "SIMULATOR") + set(SDK_NAME iphonesimulator) + if(NOT ARCHS) + set(ARCHS i386) + set(APPLE_TARGET_TRIPLE_INT i386-apple-ios${DEPLOYMENT_TARGET}-simulator) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) + endif() + message(DEPRECATION "SIMULATOR IS DEPRECATED. Consider using SIMULATOR64 instead.") +elseif(PLATFORM_INT STREQUAL "SIMULATOR64") + set(SDK_NAME iphonesimulator) + if(NOT ARCHS) + set(ARCHS x86_64) + set(APPLE_TARGET_TRIPLE_INT x86_64-apple-ios${DEPLOYMENT_TARGET}-simulator) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) + endif() +elseif(PLATFORM_INT STREQUAL "SIMULATORARM64") + set(SDK_NAME iphonesimulator) + if(NOT ARCHS) + set(ARCHS arm64) + set(APPLE_TARGET_TRIPLE_INT aarch64-apple-ios${DEPLOYMENT_TARGET}-simulator) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-simulator) + endif() +elseif(PLATFORM_INT STREQUAL "TVOS") + set(SDK_NAME appletvos) + if(NOT ARCHS) + set(ARCHS arm64) + set(APPLE_TARGET_TRIPLE_INT aarch64-apple-tvos${DEPLOYMENT_TARGET}) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}) + endif() +elseif (PLATFORM_INT STREQUAL "TVOSCOMBINED") + set(SDK_NAME appletvos) + if(MODERN_CMAKE) + if(NOT ARCHS) + set(ARCHS arm64 x86_64) + set(APPLE_TARGET_TRIPLE_INT aarch64-x86_64-apple-tvos${DEPLOYMENT_TARGET}) + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=appletvos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=appletvsimulator*] "x86_64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=appletvos*] "arm64") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=appletvsimulator*] "x86_64") + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}) + endif() + else() + message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the TVOSCOMBINED setting work") + endif() +elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") + set(SDK_NAME appletvsimulator) + if(NOT ARCHS) + set(ARCHS x86_64) + set(APPLE_TARGET_TRIPLE_INT x86_64-apple-tvos${DEPLOYMENT_TARGET}-simulator) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-tvos${DEPLOYMENT_TARGET}-simulator) + endif() +elseif(PLATFORM_INT STREQUAL "WATCHOS") + set(SDK_NAME watchos) + if(NOT ARCHS) + if (XCODE_VERSION_INT VERSION_GREATER 10.0) + set(ARCHS armv7k arm64_32) + set(APPLE_TARGET_TRIPLE_INT aarch64_32-apple-watchos${DEPLOYMENT_TARGET}) + else() + set(ARCHS armv7k) + set(APPLE_TARGET_TRIPLE_INT arm-apple-watchos${DEPLOYMENT_TARGET}) + endif() + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}) + endif() +elseif(PLATFORM_INT STREQUAL "WATCHOSCOMBINED") + set(SDK_NAME watchos) + if(MODERN_CMAKE) + if(NOT ARCHS) + if (XCODE_VERSION_INT VERSION_GREATER 10.0) + set(ARCHS armv7k arm64_32 i386) + set(APPLE_TARGET_TRIPLE_INT aarch64_32-i386-apple-watchos${DEPLOYMENT_TARGET}) + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchos*] "armv7k arm64_32") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchsimulator*] "i386") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchos*] "armv7k arm64_32") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchsimulator*] "i386") + else() + set(ARCHS armv7k i386) + set(APPLE_TARGET_TRIPLE_INT arm-i386-apple-watchos${DEPLOYMENT_TARGET}) + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchos*] "armv7k") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=watchsimulator*] "i386") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchos*] "armv7k") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=watchsimulator*] "i386") + endif() + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}) + endif() + else() + message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the WATCHOSCOMBINED setting work") + endif() +elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") + set(SDK_NAME watchsimulator) + if(NOT ARCHS) + set(ARCHS i386) + set(APPLE_TARGET_TRIPLE_INT i386-apple-watchos${DEPLOYMENT_TARGET}-simulator) + else() + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-watchos${DEPLOYMENT_TARGET}-simulator) + endif() +elseif(PLATFORM_INT STREQUAL "MAC" OR PLATFORM_INT STREQUAL "MAC_CATALYST") + set(SDK_NAME macosx) + if(NOT ARCHS) + set(ARCHS x86_64) + endif() + string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") + if(PLATFORM_INT STREQUAL "MAC") + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) + elseif(PLATFORM_INT STREQUAL "MAC_CATALYST") + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-macabi) + endif() +elseif(PLATFORM_INT MATCHES "^(MAC_ARM64)$|^(MAC_CATALYST_ARM64)$") + set(SDK_NAME macosx) + if(NOT ARCHS) + set(ARCHS arm64) + endif() + string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") + if(PLATFORM_INT STREQUAL "MAC_ARM64") + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) + elseif(PLATFORM_INT STREQUAL "MAC_CATALYST_ARM64") + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-ios${DEPLOYMENT_TARGET}-macabi) + endif() +elseif(PLATFORM_INT STREQUAL "MAC_UNIVERSAL") + set(SDK_NAME macosx) + if(NOT ARCHS) + set(ARCHS "x86_64;arm64") + endif() + string(REPLACE ";" "-" ARCHS_SPLIT "${ARCHS}") + set(APPLE_TARGET_TRIPLE_INT ${ARCHS_SPLIT}-apple-macosx${DEPLOYMENT_TARGET}) +else() + message(FATAL_ERROR "Invalid PLATFORM: ${PLATFORM_INT}") +endif() + +string(REPLACE ";" " " ARCHS_SPACED "${ARCHS}") + +if(MODERN_CMAKE AND PLATFORM_INT MATCHES ".*COMBINED" AND NOT CMAKE_GENERATOR MATCHES "Xcode") + message(FATAL_ERROR "The COMBINED options only work with Xcode generator, -G Xcode") +endif() + +if(CMAKE_GENERATOR MATCHES "Xcode" AND PLATFORM_INT MATCHES "^MAC_CATALYST") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") + set(CMAKE_XCODE_ATTRIBUTE_SUPPORTED_PLATFORMS "macosx") + set(CMAKE_XCODE_EFFECTIVE_PLATFORMS "-maccatalyst") + if(NOT DEFINED MACOSX_DEPLOYMENT_TARGET) + set(CMAKE_XCODE_ATTRIBUTE_MACOSX_DEPLOYMENT_TARGET "10.15") + else() + set(CMAKE_XCODE_ATTRIBUTE_MACOSX_DEPLOYMENT_TARGET "${MACOSX_DEPLOYMENT_TARGET}") + endif() +elseif(CMAKE_GENERATOR MATCHES "Xcode") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") + set(CMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET "${DEPLOYMENT_TARGET}") + if(NOT PLATFORM_INT MATCHES ".*COMBINED") + set(CMAKE_XCODE_ATTRIBUTE_ARCHS[sdk=${SDK_NAME}*] "${ARCHS_SPACED}") + set(CMAKE_XCODE_ATTRIBUTE_VALID_ARCHS[sdk=${SDK_NAME}*] "${ARCHS_SPACED}") + endif() +endif() + +# If the user did not specify the SDK root to use, then query xcodebuild for it. +if(DEFINED CMAKE_OSX_SYSROOT_INT) + # Environment variables are always preserved. + set(ENV{_CMAKE_OSX_SYSROOT_INT} "${CMAKE_OSX_SYSROOT_INT}") +elseif(DEFINED ENV{_CMAKE_OSX_SYSROOT_INT}) + set(CMAKE_OSX_SYSROOT_INT "$ENV{_CMAKE_OSX_SYSROOT_INT}") +elseif(NOT DEFINED CMAKE_OSX_SYSROOT_INT) + execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -version -sdk ${SDK_NAME} Path + OUTPUT_VARIABLE CMAKE_OSX_SYSROOT_INT + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() + +if (NOT DEFINED CMAKE_OSX_SYSROOT_INT AND NOT DEFINED CMAKE_OSX_SYSROOT) + message(SEND_ERROR "Please make sure that Xcode is installed and that the toolchain" + "is pointing to the correct path. Please run:" + "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" + "and see if that fixes the problem for you.") + message(FATAL_ERROR "Invalid CMAKE_OSX_SYSROOT: ${CMAKE_OSX_SYSROOT} " + "does not exist.") +elseif(DEFINED CMAKE_OSX_SYSROOT_INT) + set(CMAKE_OSX_SYSROOT_INT "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") + # Specify the location or name of the platform SDK to be used in CMAKE_OSX_SYSROOT. + set(CMAKE_OSX_SYSROOT "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") +endif() + +# Use bitcode or not +if(NOT DEFINED ENABLE_BITCODE AND NOT ARCHS MATCHES "((^|;|, )(i386|x86_64))+") + # Unless specified, enable bitcode support by default + message(STATUS "[DEFAULTS] Enabling bitcode support by default. ENABLE_BITCODE not provided!") + set(ENABLE_BITCODE ON) +elseif(NOT DEFINED ENABLE_BITCODE) + message(STATUS "[DEFAULTS] Disabling bitcode support by default on simulators. ENABLE_BITCODE not provided for override!") + set(ENABLE_BITCODE OFF) +endif() +set(ENABLE_BITCODE_INT ${ENABLE_BITCODE} CACHE BOOL + "Whether or not to enable bitcode" FORCE) +# Use ARC or not +if(NOT DEFINED ENABLE_ARC) + # Unless specified, enable ARC support by default + set(ENABLE_ARC ON) + message(STATUS "[DEFAULTS] Enabling ARC support by default. ENABLE_ARC not provided!") +endif() +set(ENABLE_ARC_INT ${ENABLE_ARC} CACHE BOOL "Whether or not to enable ARC" FORCE) +# Use hidden visibility or not +if(NOT DEFINED ENABLE_VISIBILITY) + # Unless specified, disable symbols visibility by default + set(ENABLE_VISIBILITY OFF) + message(STATUS "[DEFAULTS] Hiding symbols visibility by default. ENABLE_VISIBILITY not provided!") +endif() +set(ENABLE_VISIBILITY_INT ${ENABLE_VISIBILITY} CACHE BOOL "Whether or not to hide symbols from the dynamic linker (-fvisibility=hidden)" FORCE) +# Set strict compiler checks or not +if(NOT DEFINED ENABLE_STRICT_TRY_COMPILE) + # Unless specified, disable strict try_compile() + set(ENABLE_STRICT_TRY_COMPILE OFF) + message(STATUS "[DEFAULTS] Using NON-strict compiler checks by default. ENABLE_STRICT_TRY_COMPILE not provided!") +endif() +set(ENABLE_STRICT_TRY_COMPILE_INT ${ENABLE_STRICT_TRY_COMPILE} CACHE BOOL + "Whether or not to use strict compiler checks" FORCE) + +# Get the SDK version information. +if(DEFINED SDK_VERSION) + # Environment variables are always preserved. + set(ENV{_SDK_VERSION} "${SDK_VERSION}") +elseif(DEFINED ENV{_SDK_VERSION}) + set(SDK_VERSION "$ENV{_SDK_VERSION}") +elseif(NOT DEFINED SDK_VERSION) + execute_process(COMMAND ${XCODEBUILD_EXECUTABLE} -sdk ${CMAKE_OSX_SYSROOT_INT} -version SDKVersion + OUTPUT_VARIABLE SDK_VERSION + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() + +# Find the Developer root for the specific iOS platform being compiled for +# from CMAKE_OSX_SYSROOT. Should be ../../ from SDK specified in +# CMAKE_OSX_SYSROOT. There does not appear to be a direct way to obtain +# this information from xcrun or xcodebuild. +if (NOT DEFINED CMAKE_DEVELOPER_ROOT AND NOT CMAKE_GENERATOR MATCHES "Xcode") + get_filename_component(PLATFORM_SDK_DIR ${CMAKE_OSX_SYSROOT_INT} PATH) + get_filename_component(CMAKE_DEVELOPER_ROOT ${PLATFORM_SDK_DIR} PATH) + if (NOT EXISTS "${CMAKE_DEVELOPER_ROOT}") + message(FATAL_ERROR "Invalid CMAKE_DEVELOPER_ROOT: ${CMAKE_DEVELOPER_ROOT} does not exist.") + endif() +endif() + +# Find the C & C++ compilers for the specified SDK. +if(DEFINED CMAKE_C_COMPILER) + # Environment variables are always preserved. + set(ENV{_CMAKE_C_COMPILER} "${CMAKE_C_COMPILER}") +elseif(DEFINED ENV{_CMAKE_C_COMPILER}) + set(CMAKE_C_COMPILER "$ENV{_CMAKE_C_COMPILER}") + set(CMAKE_ASM_COMPILER ${CMAKE_C_COMPILER}) +elseif(NOT DEFINED CMAKE_C_COMPILER) + execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find clang + OUTPUT_VARIABLE CMAKE_C_COMPILER + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + set(CMAKE_ASM_COMPILER ${CMAKE_C_COMPILER}) +endif() +if(DEFINED CMAKE_CXX_COMPILER) + # Environment variables are always preserved. + set(ENV{_CMAKE_CXX_COMPILER} "${CMAKE_CXX_COMPILER}") +elseif(DEFINED ENV{_CMAKE_CXX_COMPILER}) + set(CMAKE_CXX_COMPILER "$ENV{_CMAKE_CXX_COMPILER}") +elseif(NOT DEFINED CMAKE_CXX_COMPILER) + execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find clang++ + OUTPUT_VARIABLE CMAKE_CXX_COMPILER + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() +# Find (Apple's) libtool. +if(DEFINED BUILD_LIBTOOL) + # Environment variables are always preserved. + set(ENV{_BUILD_LIBTOOL} "${BUILD_LIBTOOL}") +elseif(DEFINED ENV{_BUILD_LIBTOOL}) + set(BUILD_LIBTOOL "$ENV{_BUILD_LIBTOOL}") +elseif(NOT DEFINED BUILD_LIBTOOL) + execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find libtool + OUTPUT_VARIABLE BUILD_LIBTOOL + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) +endif() +# Find the toolchain's provided install_name_tool if none is found on the host +if(DEFINED CMAKE_INSTALL_NAME_TOOL) + # Environment variables are always preserved. + set(ENV{_CMAKE_INSTALL_NAME_TOOL} "${CMAKE_INSTALL_NAME_TOOL}") +elseif(DEFINED ENV{_CMAKE_INSTALL_NAME_TOOL}) + set(CMAKE_INSTALL_NAME_TOOL "$ENV{_CMAKE_INSTALL_NAME_TOOL}") +elseif(NOT DEFINED CMAKE_INSTALL_NAME_TOOL) + execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT_INT} -find install_name_tool + OUTPUT_VARIABLE CMAKE_INSTALL_NAME_TOOL_INT + ERROR_QUIET + OUTPUT_STRIP_TRAILING_WHITESPACE) + set(CMAKE_INSTALL_NAME_TOOL ${CMAKE_INSTALL_NAME_TOOL_INT} CACHE INTERNAL "") +endif() + +# Configure libtool to be used instead of ar + ranlib to build static libraries. +# This is required on Xcode 7+, but should also work on previous versions of +# Xcode. +get_property(languages GLOBAL PROPERTY ENABLED_LANGUAGES) +foreach(lang ${languages}) + set(CMAKE_${lang}_CREATE_STATIC_LIBRARY "${BUILD_LIBTOOL} -static -o " CACHE INTERNAL "") +endforeach() + +# CMake 3.14+ support building for iOS, watchOS, and tvOS out of the box. +if(MODERN_CMAKE) + if(SDK_NAME MATCHES "iphone") + set(CMAKE_SYSTEM_NAME iOS) + elseif(SDK_NAME MATCHES "macosx") + set(CMAKE_SYSTEM_NAME Darwin) + elseif(SDK_NAME MATCHES "appletv") + set(CMAKE_SYSTEM_NAME tvOS) + elseif(SDK_NAME MATCHES "watch") + set(CMAKE_SYSTEM_NAME watchOS) + endif() + # Provide flags for a combined FAT library build on newer CMake versions + if(PLATFORM_INT MATCHES ".*COMBINED") + set(CMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "NO") + set(CMAKE_IOS_INSTALL_COMBINED YES) + endif() +elseif(NOT DEFINED CMAKE_SYSTEM_NAME AND ${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.10") + # Legacy code path prior to CMake 3.14 or fallback if no CMAKE_SYSTEM_NAME specified + set(CMAKE_SYSTEM_NAME iOS) +elseif(NOT DEFINED CMAKE_SYSTEM_NAME) + # Legacy code path before CMake 3.14 or fallback if no CMAKE_SYSTEM_NAME specified + set(CMAKE_SYSTEM_NAME Darwin) +endif() +# Standard settings. +set(CMAKE_SYSTEM_VERSION ${SDK_VERSION} CACHE INTERNAL "") +set(UNIX ON CACHE BOOL "") +set(APPLE ON CACHE BOOL "") +if(PLATFORM STREQUAL "MAC" OR PLATFORM STREQUAL "MAC_ARM64" OR PLATFORM STREQUAL "MAC_UNIVERSAL") + set(IOS OFF CACHE BOOL "") + set(MACOS ON CACHE BOOL "") +elseif(PLATFORM STREQUAL "MAC_CATALYST" OR PLATFORM STREQUAL "MAC_CATALYST_ARM64") + set(IOS ON CACHE BOOL "") + set(MACOS ON CACHE BOOL "") +else() + set(IOS ON CACHE BOOL "") +endif() +set(CMAKE_AR ar CACHE FILEPATH "" FORCE) +set(CMAKE_RANLIB ranlib CACHE FILEPATH "" FORCE) +set(CMAKE_STRIP strip CACHE FILEPATH "" FORCE) +# Set the architectures for which to build. +set(CMAKE_OSX_ARCHITECTURES ${ARCHS} CACHE INTERNAL "") +# Change the type of target generated for try_compile() so it'll work when cross-compiling, weak compiler checks +if(NOT ENABLE_STRICT_TRY_COMPILE_INT) + set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) +endif() +# All iOS/Darwin specific settings - some may be redundant. +if (NOT DEFINED CMAKE_MACOSX_BUNDLE) + set(CMAKE_MACOSX_BUNDLE YES) +endif() +set(CMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED "NO") +set(CMAKE_SHARED_LIBRARY_PREFIX "lib") +set(CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") +set(CMAKE_SHARED_MODULE_PREFIX "lib") +set(CMAKE_SHARED_MODULE_SUFFIX ".so") +set(CMAKE_C_COMPILER_ABI ELF) +set(CMAKE_CXX_COMPILER_ABI ELF) +set(CMAKE_C_HAS_ISYSROOT 1) +set(CMAKE_CXX_HAS_ISYSROOT 1) +set(CMAKE_MODULE_EXISTS 1) +set(CMAKE_DL_LIBS "") +set(CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") +set(CMAKE_C_OSX_CURRENT_VERSION_FLAG "-current_version ") +set(CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG "${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}") +set(CMAKE_CXX_OSX_CURRENT_VERSION_FLAG "${CMAKE_C_OSX_CURRENT_VERSION_FLAG}") + +if(ARCHS MATCHES "((^|;|, )(arm64|arm64e|x86_64))+") + set(CMAKE_C_SIZEOF_DATA_PTR 8) + set(CMAKE_CXX_SIZEOF_DATA_PTR 8) + if(ARCHS MATCHES "((^|;|, )(arm64|arm64e))+") + set(CMAKE_SYSTEM_PROCESSOR "aarch64") + else() + set(CMAKE_SYSTEM_PROCESSOR "x86_64") + endif() +else() + set(CMAKE_C_SIZEOF_DATA_PTR 4) + set(CMAKE_CXX_SIZEOF_DATA_PTR 4) + set(CMAKE_SYSTEM_PROCESSOR "arm") +endif() + +# Note that only Xcode 7+ supports the newer more specific: +# -m${SDK_NAME}-version-min flags, older versions of Xcode use: +# -m(ios/ios-simulator)-version-min instead. +if(${CMAKE_VERSION} VERSION_LESS "3.11") + if(PLATFORM_INT STREQUAL "OS" OR PLATFORM_INT STREQUAL "OS64") + if(XCODE_VERSION_INT VERSION_LESS 7.0) + set(SDK_NAME_VERSION_FLAGS + "-mios-version-min=${DEPLOYMENT_TARGET}") + else() + # Xcode 7.0+ uses flags we can build directly from SDK_NAME. + set(SDK_NAME_VERSION_FLAGS + "-m${SDK_NAME}-version-min=${DEPLOYMENT_TARGET}") + endif() + elseif(PLATFORM_INT STREQUAL "TVOS") + set(SDK_NAME_VERSION_FLAGS + "-mtvos-version-min=${DEPLOYMENT_TARGET}") + elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") + set(SDK_NAME_VERSION_FLAGS + "-mtvos-simulator-version-min=${DEPLOYMENT_TARGET}") + elseif(PLATFORM_INT STREQUAL "WATCHOS") + set(SDK_NAME_VERSION_FLAGS + "-mwatchos-version-min=${DEPLOYMENT_TARGET}") + elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") + set(SDK_NAME_VERSION_FLAGS + "-mwatchos-simulator-version-min=${DEPLOYMENT_TARGET}") + elseif(PLATFORM_INT STREQUAL "MAC") + set(SDK_NAME_VERSION_FLAGS + "-mmacosx-version-min=${DEPLOYMENT_TARGET}") + else() + # SIMULATOR or SIMULATOR64 both use -mios-simulator-version-min. + set(SDK_NAME_VERSION_FLAGS + "-mios-simulator-version-min=${DEPLOYMENT_TARGET}") + endif() +elseif(NOT PLATFORM_INT MATCHES "^MAC_CATALYST") + # Newer versions of CMake sets the version min flags correctly, skip this for Mac Catalyst targets + set(CMAKE_OSX_DEPLOYMENT_TARGET ${DEPLOYMENT_TARGET}) +endif() + +if(DEFINED APPLE_TARGET_TRIPLE_INT) + set(APPLE_TARGET_TRIPLE ${APPLE_TARGET_TRIPLE_INT} CACHE INTERNAL "") + set(CMAKE_C_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) + set(CMAKE_CXX_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) + set(CMAKE_ASM_COMPILER_TARGET ${APPLE_TARGET_TRIPLE}) +endif() + +if(PLATFORM_INT MATCHES "^MAC_CATALYST") + set(C_TARGET_FLAGS "-isystem ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/usr/include -iframework ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/System/Library/Frameworks") +endif() + +if(ENABLE_BITCODE_INT) + set(BITCODE "-fembed-bitcode") + set(CMAKE_XCODE_ATTRIBUTE_BITCODE_GENERATION_MODE "bitcode") + set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "YES") +else() + set(BITCODE "") + set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE "NO") +endif() + +if(ENABLE_ARC_INT) + set(FOBJC_ARC "-fobjc-arc") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC "YES") +else() + set(FOBJC_ARC "-fno-objc-arc") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC "NO") +endif() + +if(NAMED_LANGUAGE_SUPPORT_INT) + set(OBJC_VARS "-fobjc-abi-version=2 -DOBJC_OLD_DISPATCH_PROTOTYPES=0") + set(OBJC_LEGACY_VARS "") +else() + set(OBJC_VARS "") + set(OBJC_LEGACY_VARS "-fobjc-abi-version=2 -DOBJC_OLD_DISPATCH_PROTOTYPES=0") +endif() + +if(NOT ENABLE_VISIBILITY_INT) + foreach(lang ${languages}) + set(CMAKE_${lang}_VISIBILITY_PRESET "hidden" CACHE INTERNAL "") + endforeach() + set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN "YES") + set(VISIBILITY "-fvisibility=hidden -fvisibility-inlines-hidden") +else() + foreach(lang ${languages}) + set(CMAKE_${lang}_VISIBILITY_PRESET "default" CACHE INTERNAL "") + endforeach() + set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN "NO") + set(VISIBILITY "-fvisibility=default") +endif() + +if(DEFINED APPLE_TARGET_TRIPLE) + set(APPLE_TARGET_TRIPLE_FLAG "-target ${APPLE_TARGET_TRIPLE}") +endif() + +#Check if Xcode generator is used since that will handle these flags automagically +if(CMAKE_GENERATOR MATCHES "Xcode") + message(STATUS "Not setting any manual command-line buildflags, since Xcode is selected as the generator. Modifying the Xcode build-settings directly instead.") +else() + set(CMAKE_C_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${OBJC_LEGACY_VARS} ${BITCODE} ${VISIBILITY} ${CMAKE_C_FLAGS}") + set(CMAKE_C_FLAGS_DEBUG "-O0 -g ${CMAKE_C_FLAGS_DEBUG}") + set(CMAKE_C_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_C_FLAGS_MINSIZEREL}") + set(CMAKE_C_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_C_FLAGS_RELWITHDEBINFO}") + set(CMAKE_C_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_C_FLAGS_RELEASE}") + set(CMAKE_CXX_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${OBJC_LEGACY_VARS} ${BITCODE} ${VISIBILITY} ${CMAKE_CXX_FLAGS}") + set(CMAKE_CXX_FLAGS_DEBUG "-O0 -g ${CMAKE_CXX_FLAGS_DEBUG}") + set(CMAKE_CXX_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_CXX_FLAGS_MINSIZEREL}") + set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") + set(CMAKE_CXX_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_CXX_FLAGS_RELEASE}") + if(NAMED_LANGUAGE_SUPPORT_INT) + set(CMAKE_OBJC_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} ${FOBJC_ARC} ${OBJC_VARS} ${CMAKE_OBJC_FLAGS}") + set(CMAKE_OBJC_FLAGS_DEBUG "-O0 -g ${CMAKE_OBJC_FLAGS_DEBUG}") + set(CMAKE_OBJC_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_OBJC_FLAGS_MINSIZEREL}") + set(CMAKE_OBJC_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_OBJC_FLAGS_RELWITHDEBINFO}") + set(CMAKE_OBJC_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_OBJC_FLAGS_RELEASE}") + set(CMAKE_OBJCXX_FLAGS "${C_TARGET_FLAGS} ${APPLE_TARGET_TRIPLE_FLAG} ${SDK_NAME_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} ${FOBJC_ARC} ${OBJC_VARS} ${CMAKE_OBJCXX_FLAGS}") + set(CMAKE_OBJCXX_FLAGS_DEBUG "-O0 -g ${CMAKE_OBJCXX_FLAGS_DEBUG}") + set(CMAKE_OBJCXX_FLAGS_MINSIZEREL "-DNDEBUG -Os ${CMAKE_OBJCXX_FLAGS_MINSIZEREL}") + set(CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO "-DNDEBUG -O2 -g ${CMAKE_OBJCXX_FLAGS_RELWITHDEBINFO}") + set(CMAKE_OBJCXX_FLAGS_RELEASE "-DNDEBUG -O3 ${CMAKE_OBJCXX_FLAGS_RELEASE}") + endif() + set(CMAKE_C_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}") + set(CMAKE_CXX_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}") + if(NAMED_LANGUAGE_SUPPORT_INT) + set(CMAKE_OBJC_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_OBJC_LINK_FLAGS}") + set(CMAKE_OBJCXX_LINK_FLAGS "${C_TARGET_FLAGS} ${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_OBJCXX_LINK_FLAGS}") + endif() + set(CMAKE_ASM_FLAGS "${CMAKE_C_FLAGS} -x assembler-with-cpp -arch ${CMAKE_OSX_ARCHITECTURES} ${APPLE_TARGET_TRIPLE_FLAG}") +endif() + +## Print status messages to inform of the current state +message(STATUS "Configuring ${SDK_NAME} build for platform: ${PLATFORM_INT}, architecture(s): ${ARCHS}") +message(STATUS "Using SDK: ${CMAKE_OSX_SYSROOT_INT}") +message(STATUS "Using C compiler: ${CMAKE_C_COMPILER}") +message(STATUS "Using CXX compiler: ${CMAKE_CXX_COMPILER}") +message(STATUS "Using libtool: ${BUILD_LIBTOOL}") +message(STATUS "Using install name tool: ${CMAKE_INSTALL_NAME_TOOL}") +if(DEFINED APPLE_TARGET_TRIPLE) + message(STATUS "Autoconf target triple: ${APPLE_TARGET_TRIPLE}") +endif() +message(STATUS "Using minimum deployment version: ${DEPLOYMENT_TARGET}" + " (SDK version: ${SDK_VERSION})") +if(MODERN_CMAKE) + message(STATUS "Merging integrated CMake 3.14+ iOS,tvOS,watchOS,macOS toolchain(s) with this toolchain!") + if(PLATFORM_INT MATCHES ".*COMBINED") + message(STATUS "Will combine built (static) artifacts into FAT lib...") + endif() +endif() +if(CMAKE_GENERATOR MATCHES "Xcode") + message(STATUS "Using Xcode version: ${XCODE_VERSION_INT}") +endif() +message(STATUS "CMake version: ${CMAKE_VERSION}") +if(DEFINED SDK_NAME_VERSION_FLAGS) + message(STATUS "Using version flags: ${SDK_NAME_VERSION_FLAGS}") +endif() +message(STATUS "Using a data_ptr size of: ${CMAKE_CXX_SIZEOF_DATA_PTR}") +if(ENABLE_BITCODE_INT) + message(STATUS "Bitcode: Enabled") +else() + message(STATUS "Bitcode: Disabled") +endif() + +if(ENABLE_ARC_INT) + message(STATUS "ARC: Enabled") +else() + message(STATUS "ARC: Disabled") +endif() + +if(ENABLE_VISIBILITY_INT) + message(STATUS "Hiding symbols: Disabled") +else() + message(STATUS "Hiding symbols: Enabled") +endif() + +# Set global properties +set_property(GLOBAL PROPERTY PLATFORM "${PLATFORM}") +set_property(GLOBAL PROPERTY APPLE_TARGET_TRIPLE "${APPLE_TARGET_TRIPLE_INT}") +set_property(GLOBAL PROPERTY SDK_VERSION "${SDK_VERSION}") +set_property(GLOBAL PROPERTY XCODE_VERSION "${XCODE_VERSION_INT}") +set_property(GLOBAL PROPERTY OSX_ARCHITECTURES "${CMAKE_OSX_ARCHITECTURES}") + +# Export configurable variables for the try_compile() command. +set(CMAKE_TRY_COMPILE_PLATFORM_VARIABLES + PLATFORM + XCODE_VERSION_INT + SDK_VERSION + NAMED_LANGUAGE_SUPPORT + DEPLOYMENT_TARGET + CMAKE_DEVELOPER_ROOT + CMAKE_OSX_SYSROOT_INT + ENABLE_BITCODE + ENABLE_ARC + CMAKE_ASM_COMPILER + CMAKE_C_COMPILER + CMAKE_C_COMPILER_TARGET + CMAKE_CXX_COMPILER + CMAKE_CXX_COMPILER_TARGET + BUILD_LIBTOOL + CMAKE_INSTALL_NAME_TOOL + CMAKE_C_FLAGS + CMAKE_C_DEBUG + CMAKE_C_MINSIZEREL + CMAKE_C_RELWITHDEBINFO + CMAKE_C_RELEASE + CMAKE_CXX_FLAGS + CMAKE_CXX_FLAGS_DEBUG + CMAKE_CXX_FLAGS_MINSIZEREL + CMAKE_CXX_FLAGS_RELWITHDEBINFO + CMAKE_CXX_FLAGS_RELEASE + CMAKE_C_LINK_FLAGS + CMAKE_CXX_LINK_FLAGS + CMAKE_ASM_FLAGS +) + +if(NAMED_LANGUAGE_SUPPORT_INT) + list(APPEND CMAKE_TRY_COMPILE_PLATFORM_VARIABLES + CMAKE_OBJC_FLAGS + CMAKE_OBJC_DEBUG + CMAKE_OBJC_MINSIZEREL + CMAKE_OBJC_RELWITHDEBINFO + CMAKE_OBJC_RELEASE + CMAKE_OBJCXX_FLAGS + CMAKE_OBJCXX_DEBUG + CMAKE_OBJCXX_MINSIZEREL + CMAKE_OBJCXX_RELWITHDEBINFO + CMAKE_OBJCXX_RELEASE + CMAKE_OBJC_LINK_FLAGS + CMAKE_OBJCXX_LINK_FLAGS + ) +endif() + +set(CMAKE_PLATFORM_HAS_INSTALLNAME 1) +set(CMAKE_SHARED_LINKER_FLAGS "-rpath @executable_path/Frameworks -rpath @loader_path/Frameworks") +set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") +set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle -Wl,-headerpad_max_install_names") +set(CMAKE_SHARED_MODULE_LOADER_C_FLAG "-Wl,-bundle_loader,") +set(CMAKE_SHARED_MODULE_LOADER_CXX_FLAG "-Wl,-bundle_loader,") +set(CMAKE_FIND_LIBRARY_SUFFIXES ".tbd" ".dylib" ".so" ".a") +set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-install_name") + +# Set the find root to the SDK developer roots. +# Note: CMAKE_FIND_ROOT_PATH is only useful when cross-compiling. Thus, do not set on macOS builds. +if(NOT PLATFORM_INT MATCHES "^MAC.*$") + list(APPEND CMAKE_FIND_ROOT_PATH "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") + set(CMAKE_IGNORE_PATH "/System/Library/Frameworks;/usr/local/lib" CACHE INTERNAL "") +endif() + +# Default to searching for frameworks first. +set(CMAKE_FIND_FRAMEWORK FIRST) + +# Set up the default search directories for frameworks. +if(PLATFORM_INT MATCHES "^MAC_CATALYST") + set(CMAKE_FRAMEWORK_PATH + ${CMAKE_DEVELOPER_ROOT}/Library/PrivateFrameworks + ${CMAKE_OSX_SYSROOT_INT}/System/Library/Frameworks + ${CMAKE_OSX_SYSROOT_INT}/System/iOSSupport/System/Library/Frameworks + ${CMAKE_FRAMEWORK_PATH} CACHE INTERNAL "") +else() + set(CMAKE_FRAMEWORK_PATH + ${CMAKE_DEVELOPER_ROOT}/Library/PrivateFrameworks + ${CMAKE_OSX_SYSROOT_INT}/System/Library/Frameworks + ${CMAKE_FRAMEWORK_PATH} CACHE INTERNAL "") +endif() + +# By default, search both the specified iOS SDK and the remainder of the host filesystem. +if(NOT CMAKE_FIND_ROOT_PATH_MODE_PROGRAM) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH CACHE INTERNAL "") +endif() +if(NOT CMAKE_FIND_ROOT_PATH_MODE_LIBRARY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH CACHE INTERNAL "") +endif() +if(NOT CMAKE_FIND_ROOT_PATH_MODE_INCLUDE) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH CACHE INTERNAL "") +endif() +if(NOT CMAKE_FIND_ROOT_PATH_MODE_PACKAGE) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE BOTH CACHE INTERNAL "") +endif() + +# +# Some helper-macros below to simplify and beautify the CMakeFile +# + +# This little macro lets you set any Xcode specific property. +macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE XCODE_RELVERSION) + set(XCODE_RELVERSION_I "${XCODE_RELVERSION}") + if(XCODE_RELVERSION_I STREQUAL "All") + set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} "${XCODE_VALUE}") + else() + set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY}[variant=${XCODE_RELVERSION_I}] "${XCODE_VALUE}") + endif() +endmacro(set_xcode_property) + +# This macro lets you find executable programs on the host system. +macro(find_host_package) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) + set(_TOOLCHAIN_IOS ${IOS}) + set(IOS OFF) + find_package(${ARGN}) + set(IOS ${_TOOLCHAIN_IOS}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE BOTH) +endmacro(find_host_package) diff --git a/external/libhv/libhv-1.3.2/cmake/libhvConfig.cmake b/external/libhv/libhv-1.3.2/cmake/libhvConfig.cmake new file mode 100644 index 0000000..9088115 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cmake/libhvConfig.cmake @@ -0,0 +1,87 @@ + +include(SelectLibraryConfigurations) + +find_path(libhv_INCLUDE_DIRS hv/hv.h) +message("libhv_INCLUDE_DIRS: " ${libhv_INCLUDE_DIRS}) + +find_library(libhv_LIBRARY_RELEASE NAMES hv PATHS "${CMAKE_CURRENT_LIST_DIR}/../../lib" NO_DEFAULT_PATH) + +find_library(libhv_LIBRARY_DEBUG NAMES hv PATHS "${CMAKE_CURRENT_LIST_DIR}/../../debug/lib" NO_DEFAULT_PATH) +select_library_configurations(libhv) + +if(NOT libhv_LIBRARY) + set(libhv_FOUND FALSE) + set(LIBHV_FOUND FALSE) + return() +endif() + +if(WIN32) + find_file(libhv_LIBRARY_RELEASE_DLL NAMES hv.dll PATHS "${CMAKE_CURRENT_LIST_DIR}/../../bin" NO_DEFAULT_PATH) + find_file(libhv_LIBRARY_DEBUG_DLL NAMES hv.dll PATHS "${CMAKE_CURRENT_LIST_DIR}/../../debug/bin" NO_DEFAULT_PATH) +endif() + +# Manage Release Windows shared +if(EXISTS "${libhv_LIBRARY_RELEASE_DLL}") + add_library(libhv SHARED IMPORTED) + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS Release + IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE_DLL}" + IMPORTED_IMPLIB_RELEASE "${libhv_LIBRARY_RELEASE}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) +endif() + +# Manage Debug Windows shared +if(EXISTS "${libhv_LIBRARY_DEBUG_DLL}") + if(EXISTS "${libhv_LIBRARY_RELEASE_DLL}") + #message("Debug mode") + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS "Release;Debug" + IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE_DLL}" + IMPORTED_IMPLIB_RELEASE "${libhv_LIBRARY_RELEASE}" + IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG_DLL}" + IMPORTED_IMPLIB_DEBUG "${libhv_LIBRARY_DEBUG}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) + else() + add_library(libhv SHARED IMPORTED) + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS Debug + IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG_DLL}" + IMPORTED_IMPLIB_DEBUG "${libhv_LIBRARY_DEBUG}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) + endif() +endif() + +# Manage Release Windows static and Linux shared/static +if((NOT EXISTS "${libhv_LIBRARY_RELEASE_DLL}") AND (EXISTS "${libhv_LIBRARY_RELEASE}")) + add_library(libhv UNKNOWN IMPORTED) + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS Release + IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) +endif() + +# Manage Debug Windows static and Linux shared/static +if((NOT EXISTS "${libhv_LIBRARY_DEBUG_DLL}") AND (EXISTS "${libhv_LIBRARY_DEBUG}")) + if(EXISTS "${libhv_LIBRARY_RELEASE}") + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS "Release;Debug" + IMPORTED_LOCATION_RELEASE "${libhv_LIBRARY_RELEASE}" + IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) + else() + add_library(libhv UNKNOWN IMPORTED) + set_target_properties(libhv PROPERTIES + IMPORTED_CONFIGURATIONS Debug + IMPORTED_LOCATION_DEBUG "${libhv_LIBRARY_DEBUG}" + INTERFACE_INCLUDE_DIRECTORIES "${libhv_INCLUDE_DIRS}" + ) + endif() +endif() + +set(libhv_FOUND TRUE) +set(LIBHV_FOUND TRUE) diff --git a/external/libhv/libhv-1.3.2/cmake/utils.cmake b/external/libhv/libhv-1.3.2/cmake/utils.cmake new file mode 100644 index 0000000..38ff5c9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cmake/utils.cmake @@ -0,0 +1,42 @@ +include(CheckIncludeFiles) +macro(check_header header) + string(TOUPPER ${header} str1) + string(REGEX REPLACE "[/.]" "_" str2 ${str1}) + set(str3 HAVE_${str2}) + check_include_files(${header} ${str3}) + if (${str3}) + set(${str3} 1) + else() + set(${str3} 0) + endif() +endmacro() + +include(CheckSymbolExists) +macro(check_function function header) + string(TOUPPER ${function} str1) + set(str2 HAVE_${str1}) + check_symbol_exists(${function} ${header} ${str2}) + if (${str2}) + set(${str2} 1) + else() + set(${str2} 0) + endif() +endmacro() + +macro(list_source_directories srcs) + unset(tmp) + foreach(dir ${ARGN}) + aux_source_directory(${dir} tmp) + endforeach() + set(${srcs} ${tmp}) + list(FILTER ${srcs} EXCLUDE REGEX ".*_test\\.c") +endmacro() + +macro(glob_headers_and_sources files) + unset(tmp) + foreach(dir ${ARGN}) + file(GLOB tmp ${dir}/*.h ${dir}/*.c ${dir}/*.hpp ${dir}/*.cpp) + list(APPEND ${files} ${tmp}) + endforeach() + list(FILTER ${files} EXCLUDE REGEX ".*_test\\.c") +endmacro() diff --git a/external/libhv/libhv-1.3.2/cmake/vars.cmake b/external/libhv/libhv-1.3.2/cmake/vars.cmake new file mode 100644 index 0000000..20a6e65 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cmake/vars.cmake @@ -0,0 +1,110 @@ +# see Makefile.vars + +set(BASE_HEADERS + base/hplatform.h + base/hdef.h + base/hatomic.h + base/herr.h + base/htime.h + base/hmath.h + base/hbase.h + base/hversion.h + base/hsysinfo.h + base/hproc.h + base/hthread.h + base/hmutex.h + base/hsocket.h + base/hlog.h + base/hbuf.h + base/hmain.h + base/hendian.h +) + +set(SSL_HEADERS + ssl/hssl.h +) + +set(EVENT_HEADERS + event/hloop.h + event/nlog.h +) + +set(UTIL_HEADERS + util/base64.h + util/md5.h + util/sha1.h +) + +set(CPPUTIL_HEADERS + cpputil/hmap.h + cpputil/hstring.h + cpputil/hfile.h + cpputil/hpath.h + cpputil/hdir.h + cpputil/hurl.h + cpputil/hscope.h + cpputil/hthreadpool.h + cpputil/hasync.h + cpputil/hobjectpool.h + cpputil/ifconfig.h + cpputil/iniparser.h + cpputil/json.hpp + cpputil/singleton.h + cpputil/ThreadLocalStorage.h +) + +set(EVPP_HEADERS + evpp/Buffer.h + evpp/Channel.h + evpp/Event.h + evpp/EventLoop.h + evpp/EventLoopThread.h + evpp/EventLoopThreadPool.h + evpp/Status.h + evpp/TcpClient.h + evpp/TcpServer.h + evpp/UdpClient.h + evpp/UdpServer.h +) + +set(PROTOCOL_HEADERS + protocol/icmp.h + protocol/dns.h + protocol/ftp.h + protocol/smtp.h +) + +set(HTTP_HEADERS + http/httpdef.h + http/wsdef.h + http/http_content.h + http/HttpMessage.h + http/HttpParser.h + http/WebSocketParser.h + http/WebSocketChannel.h +) + +set(HTTP2_HEADERS + http/http2def.h + http/grpcdef.h +) + +set(HTTP_CLIENT_HEADERS + http/client/HttpClient.h + http/client/requests.h + http/client/axios.h + http/client/AsyncHttpClient.h + http/client/WebSocketClient.h) + +set(HTTP_SERVER_HEADERS + http/server/HttpServer.h + http/server/HttpService.h + http/server/HttpContext.h + http/server/HttpResponseWriter.h + http/server/WebSocketServer.h +) + +set(MQTT_HEADERS + mqtt/mqtt_protocol.h + mqtt/mqtt_client.h +) diff --git a/external/libhv/libhv-1.3.2/config.ini b/external/libhv/libhv-1.3.2/config.ini new file mode 100644 index 0000000..f7877fe --- /dev/null +++ b/external/libhv/libhv-1.3.2/config.ini @@ -0,0 +1,37 @@ +# Don't modify this file, you should modify config.mk or +# run ./configure --with-MODULE --enable-FEATURE + +PREFIX=/usr/local +INSTALL_INCDIR=$(PREFIX)/include/hv +INSTALL_LIBDIR=$(PREFIX)/lib + +# modules +# include icmp dns ftp smtp +WITH_PROTOCOL=no + +WITH_EVPP=yes +WITH_HTTP=yes +WITH_HTTP_SERVER=yes +WITH_HTTP_CLIENT=yes +WITH_MQTT=no + +# features +# base/hsocket.h: Unix Domain Socket +ENABLE_UDS=no +# base/RAII.cpp: Windows MiniDumpWriteDump +ENABLE_WINDUMP=no +# http/http_content.h: KeyValue,QueryParams,MultiPart +USE_MULTIMAP=no + +# dependencies +# for http/client +WITH_CURL=no +# for http2 +WITH_NGHTTP2=no +# for SSL/TLS +WITH_OPENSSL=no +WITH_GNUTLS=no +WITH_MBEDTLS=no + +# rudp +WITH_KCP=no diff --git a/external/libhv/libhv-1.3.2/configure b/external/libhv/libhv-1.3.2/configure new file mode 100755 index 0000000..15b4489 --- /dev/null +++ b/external/libhv/libhv-1.3.2/configure @@ -0,0 +1,288 @@ +#!/bin/bash + +. "$(dirname "$0")/scripts/shini.sh" + +print_help() { + shini_parse "config.ini" + cat << END +Usage: ./configure [--option] ... + +options: + --prefix=PREFIX (DEFAULT: $PREFIX) + --incdir=INSTALL_INCDIR (DEFAULT: $PREFIX/include/hv) + --libdir=INSTALL_LIBDIR (DEFAULT: $PREFIX/lib) + + --with-MODULE + --without-MODULE + --enable-FEATURE + --disable-FEATURE + +modules: + --with-protocol compile protocol module? (DEFAULT: $WITH_PROTOCOL) + --with-evpp compile evpp module? (DEFAULT: $WITH_EVPP) + --with-http compile http module? (DEFAULT: $WITH_HTTP) + --with-http-client compile http client module? (DEFAULT: $WITH_HTTP_CLIENT) + --with-http-server compile http server module? (DEFAULT: $WITH_HTTP_SERVER) + --with-mqtt compile mqtt module? (DEFAULT: $WITH_MQTT) + +features: + --enable-uds enable Unix Domain Socket? (DEFAULT: $ENABLE_UDS) + --enable-windump enable Windows coredump? (DEFAULT: $ENABLE_WINDUMP) + +dependencies: + --with-curl compile with curl? (DEFAULT: $WITH_CURL) + --with-nghttp2 compile with nghttp2? (DEFAULT: $WITH_NGHTTP2) + --with-openssl compile with openssl? (DEFAULT: $WITH_OPENSSL) + --with-gnutls compile with gnutls? (DEFAULT: $WITH_GNUTLS) + --with-mbedtls compile with mbedtls? (DEFAULT: $WITH_MBEDTLS) + +rudp: + --with-kcp compile with kcp? (DEFAULT: $WITH_KCP) + +END +} + +mkdir tmp 2>/dev/null +while [ -n "$1" ] +do + opt="$1" + KEY="" + VAL=yes + case $opt in + --help) + print_help + exit 0 + ;; + --prefix=*) + KEY="PREFIX" + VAL=${opt:9} + ;; + --incdir=*) + KEY="INSTALL_INCDIR" + VAL=${opt:9} + ;; + --libdir=*) + KEY="INSTALL_LIBDIR" + VAL=${opt:9} + ;; + --with-*) + KEY="WITH_${opt:7}" + ;; + --without-*) + KEY="WITH_${opt:10}" + VAL=no + ;; + --enable-*) + KEY="ENABLE_${opt:9}" + ;; + --disable-*) + KEY="ENABLE_${opt:10}" + VAL=no + ;; + *) + print_help + exit 255 + ;; + esac + + if [ -n $KEY ]; then + FEATURE=$(echo "$KEY" | tr "a-z-" "A-Z_") + if [ ! -f tmp/config.mk ]; then + cp config.ini tmp/config.mk + fi + shini_write "tmp/config.mk" "" "$FEATURE" "$VAL" + fi + + shift 1 +done + +# config.mk +echo "[config.mk]" +if [ -f tmp/config.mk ]; then + mv tmp/config.mk config.mk + shini_write "config.mk" "" "CONFIG_DATE" "$(date +%Y%m%d)" +fi +cat config.mk +echo "" + +# Checks for compiler +echo -e "\nchecking for compiler..." +if [ $CROSS_COMPILE ]; then + CC=${CROSS_COMPILE}gcc + CXX=${CROSS_COMPILE}g++ +fi + +if [ ! $CC ]; then + CC=gcc + CXX=g++ +fi +CC_VERSION=`$CC --version 2>&1 | head -n 1` + +echo "CC = $CC" +echo "CXX = $CXX" +echo "$CC_VERSION" + +# Checks for os +echo -e "\nchecking for os..." +HOST_OS=`uname -s` +HOST_ARCH=`uname -m` +TARGET_PLATFORM=`$CC -v 2>&1 | grep Target | sed 's/Target: //'` +TARGET_ARCH=`echo $TARGET_PLATFORM | awk -F'-' '{print $1}'` + +case $TARGET_PLATFORM in + *mingw*) TARGET_OS=Windows ;; + *android*) TARGET_OS=Android ;; + *darwin*) TARGET_OS=Darwin ;; + *) TARGET_OS=Linux ;; +esac + +echo "HOST_OS = $HOST_OS" +echo "HOST_ARCH = $HOST_ARCH" +echo "TARGET_PLATFORM = $TARGET_PLATFORM" +echo "TARGET_OS = $TARGET_OS" +echo "TARGET_ARCH = $TARGET_ARCH" + +# hconfig.h +echo -e "\n>> hconfig.h" +confile=hconfig.h +cat << END > $confile +#ifndef HV_CONFIG_H_ +#define HV_CONFIG_H_ + +END + +write_define() { +cat << END >> hconfig.h +#ifndef $macro +#define $macro $value +#endif + +END +} + +CheckHeaderExists() { +rm tmp/check 2>/dev/null +cat << END > tmp/check.c +#include <$header> + +int main() { + return 0; +} + +END +$CC -o tmp/check tmp/check.c 2>/dev/null +if [ -x tmp/check ]; then + value=1 +else + value=0 +fi +} + +CheckSymbolExists() { +CheckHeaderExists +if [ $value -eq 0 ]; then + return; +fi +rm tmp/check 2>/dev/null +cat << END > tmp/check.c +#include <$header> + +int $function(void** pp) {return 0;} +int main() { + void* p; + return $function(&p); +} + +END +$CC -o tmp/check tmp/check.c 2>/dev/null +if [ -x tmp/check ]; then + value=0 +else + value=1 +fi +} + +check_header() { +echo -n "checking for $header... " +CheckHeaderExists +if [ $value -eq 0 ]; then + echo "no" +else + echo "yes" +fi +macro=HAVE_$(echo $header | tr a-z./ A-Z__) +write_define +} + +check_function() { +echo -n "checking for $function... " +CheckSymbolExists +if [ $value -eq 0 ]; then + echo "no" +else + echo "yes" +fi +macro=HAVE_$(echo $function | tr a-z A-Z) +write_define +} + +check_option() { +value=$(eval echo \$$option) +echo "checking for $option=$value" +if [ "$value" == "yes" ]; then +cat << END >> $confile +#define $option 1 +END +else +cat << END >> $confile +/* #undef $option */ +END +fi +} + +# Checks for programs + +# Checks for libraries + +# Checks for header files +header=stdbool.h && check_header +header=stdint.h && check_header +header=stdatomic.h && check_header +header=sys/types.h && check_header +header=sys/stat.h && check_header +header=sys/time.h && check_header +header=fcntl.h && check_header +header=pthread.h && check_header +header=endian.h && check_header +header=sys/endian.h && check_header + +# Checks for functions +function=gettid && header=unistd.h && check_function +function=strlcpy && header=string.h && check_function +function=strlcat && header=string.h && check_function +function=clock_gettime && header=time.h && check_function +function=gettimeofday && header=sys/time.h && check_function +function=pthread_spin_lock && header=pthread.h && check_function +function=pthread_mutex_timedlock && header=pthread.h && check_function +function=sem_timedwait && header=semaphore.h && check_function +function=pipe && header=unistd.h && check_function +function=socketpair && header=sys/socket.h && check_function +function=eventfd && header=sys/eventfd.h && check_function +function=setproctitle && header=unistd.h && check_function + +# Checks for options +source config.mk 2>/dev/null +option=WITH_OPENSSL && check_option +option=WITH_GNUTLS && check_option +option=WITH_MBEDTLS && check_option +option=ENABLE_UDS && check_option +option=USE_MULTIMAP && check_option +option=WITH_KCP && check_option + +# end confile +cat << END >> $confile + +#endif // HV_CONFIG_H_ +END + +echo "configure done." diff --git a/external/libhv/libhv-1.3.2/cpputil/RAII.cpp b/external/libhv/libhv-1.3.2/cpputil/RAII.cpp new file mode 100644 index 0000000..078380a --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/RAII.cpp @@ -0,0 +1,66 @@ +#include "hplatform.h" + +#ifdef OS_WIN +#ifdef ENABLE_WINDUMP +#include +#ifdef _MSC_VER +#pragma comment(lib,"dbghelp.lib") +#endif +static LONG UnhandledException(EXCEPTION_POINTERS *pException) { + char modulefile[256]; + GetModuleFileName(NULL, modulefile, sizeof(modulefile)); + char* pos = strrchr(modulefile, '\\'); + char* modulefilename = pos + 1; + SYSTEMTIME st; + GetLocalTime(&st); + char filename[256]; + snprintf(filename, sizeof(filename), "core_%s_%04d%02d%02d_%02d%02d%02d_%03d.dump", + modulefilename, + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); + HANDLE hDumpFile = CreateFile(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + MINIDUMP_EXCEPTION_INFORMATION dumpInfo; + dumpInfo.ExceptionPointers = pException; + dumpInfo.ThreadId = GetCurrentThreadId(); + dumpInfo.ClientPointers = TRUE; + MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL); + CloseHandle(hDumpFile); + return EXCEPTION_EXECUTE_HANDLER; +} +#endif + +#include "hsocket.h" +class WsaRAII { +public: + WsaRAII() { + WSAInit(); +#ifdef ENABLE_WINDUMP + SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)UnhandledException); +#endif + } + ~WsaRAII() { + WSADeinit(); + } +}; +static WsaRAII s_wsa; +#endif + +#ifdef WITH_CURL +#include "curl/curl.h" +#ifdef _MSC_VER +//#pragma comment(lib, "libcurl.a") +#pragma comment(lib, "ws2_32.lib") +#pragma comment(lib, "wldap32.lib") +#pragma comment(lib, "advapi32.lib") +#pragma comment(lib, "crypt32.lib") +#endif +class CurlRAII { +public: + CurlRAII() { + curl_global_init(CURL_GLOBAL_ALL); + } + ~CurlRAII() { + curl_global_cleanup(); + } +}; +static CurlRAII s_curl; +#endif diff --git a/external/libhv/libhv-1.3.2/cpputil/README.md b/external/libhv/libhv-1.3.2/cpputil/README.md new file mode 100644 index 0000000..7adad79 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/README.md @@ -0,0 +1,20 @@ +## 目录结构 + +``` +. +├── hasync.h hv::async实现 +├── hdir.h 目录(ls实现) +├── hfile.h 文件类 +├── hobjectpool.h 对象池 +├── hpath.h 路径操作 +├── hscope.h 作用域模板类 +├── hstring.h 字符串操作 +├── hthreadpool.h 线程池 +├── hurl.h URL操作 +├── ifconfig.h 网络配置(ifconfig实现) +├── iniparser.h INI解析 +├── json.hpp JSON解析 +├── singleton.h 单例模式宏 +└── ThreadLocalStorage.h 线程本地存储类 + +``` diff --git a/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.cpp b/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.cpp new file mode 100644 index 0000000..8b72786 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.cpp @@ -0,0 +1,32 @@ +#include "ThreadLocalStorage.h" + +#include "hthread.h" + +namespace hv { + +ThreadLocalStorage ThreadLocalStorage::tls[ThreadLocalStorage::MAX_NUM]; + +void ThreadLocalStorage::set(int idx, void* val) { + return tls[idx].set(val); +} + +void* ThreadLocalStorage::get(int idx) { + return tls[idx].get(); +} + +void ThreadLocalStorage::setThreadName(const char* name) { + set(THREAD_NAME, (void*)name); +} + +const char* ThreadLocalStorage::threadName() { + void* value = get(THREAD_NAME); + if (value) { + return (char*)value; + } + + static char unnamed[32] = {0}; + snprintf(unnamed, sizeof(unnamed)-1, "thread-%ld", hv_gettid()); + return unnamed; +} + +} diff --git a/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.h b/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.h new file mode 100644 index 0000000..e4ddaee --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/ThreadLocalStorage.h @@ -0,0 +1,67 @@ +#ifndef HV_THREAD_LOCAL_STORAGE_H_ +#define HV_THREAD_LOCAL_STORAGE_H_ + +#include "hexport.h" +#include "hplatform.h" + +#ifdef OS_WIN + +#define hthread_key_t DWORD +#define INVALID_HTHREAD_KEY 0xFFFFFFFF +#define hthread_key_create(pkey) *pkey = TlsAlloc() +#define hthread_key_delete TlsFree +#define hthread_get_value TlsGetValue +#define hthread_set_value TlsSetValue + +#else + +#define hthread_key_t pthread_key_t +#define INVALID_HTHREAD_KEY 0xFFFFFFFF +#define hthread_key_create(pkey) pthread_key_create(pkey, NULL) +#define hthread_key_delete pthread_key_delete +#define hthread_get_value pthread_getspecific +#define hthread_set_value pthread_setspecific + +#endif + +#ifdef __cplusplus +namespace hv { + +class HV_EXPORT ThreadLocalStorage { +public: + enum { + THREAD_NAME = 0, + EVENT_LOOP = 1, + MAX_NUM = 16, + }; + ThreadLocalStorage() { + hthread_key_create(&key); + } + + ~ThreadLocalStorage() { + hthread_key_delete(key); + } + + void set(void* val) { + hthread_set_value(key, val); + } + + void* get() { + return hthread_get_value(key); + } + + static void set(int idx, void* val); + static void* get(int idx); + + static void setThreadName(const char* name); + static const char* threadName(); + +private: + hthread_key_t key; + static ThreadLocalStorage tls[MAX_NUM]; +}; + +} +#endif + +#endif // HV_THREAD_LOCAL_STORAGE_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hasync.cpp b/external/libhv/libhv-1.3.2/cpputil/hasync.cpp new file mode 100644 index 0000000..e60685e --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hasync.cpp @@ -0,0 +1,7 @@ +#include "hasync.h" + +namespace hv { + +SINGLETON_IMPL(GlobalThreadPool) + +} diff --git a/external/libhv/libhv-1.3.2/cpputil/hasync.h b/external/libhv/libhv-1.3.2/cpputil/hasync.h new file mode 100644 index 0000000..c1ea03d --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hasync.h @@ -0,0 +1,49 @@ +#ifndef HV_ASYNC_H_ +#define HV_ASYNC_H_ + +#include "hexport.h" +#include "hthreadpool.h" +#include "singleton.h" + +namespace hv { + +class HV_EXPORT GlobalThreadPool : public HThreadPool { + SINGLETON_DECL(GlobalThreadPool) +protected: + GlobalThreadPool() : HThreadPool() {} + ~GlobalThreadPool() {} +}; + +/* + * return a future, calling future.get() will wait task done and return RetType. + * async(fn, args...) + * async(std::bind(&Class::mem_fn, &obj)) + * async(std::mem_fn(&Class::mem_fn, &obj)) + * + */ +template +auto async(Fn&& fn, Args&&... args) -> std::future { + return GlobalThreadPool::instance()->commit(std::forward(fn), std::forward(args)...); +} + +class async { +public: + static void startup(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM, + int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM, + int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) { + GlobalThreadPool* gtp = GlobalThreadPool::instance(); + if (gtp->isStarted()) return; + gtp->setMinThreadNum(min_threads); + gtp->setMaxThreadNum(max_threads); + gtp->setMaxIdleTime(max_idle_ms); + gtp->start(); + } + + static void cleanup() { + GlobalThreadPool::exitInstance(); + } +}; + +} // end namespace hv + +#endif // HV_ASYNC_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hdir.cpp b/external/libhv/libhv-1.3.2/cpputil/hdir.cpp new file mode 100644 index 0000000..4027223 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hdir.cpp @@ -0,0 +1,88 @@ +#include "hdir.h" + +#include "hplatform.h" + +#ifdef OS_WIN +//FILETIME starts from 1601-01-01 UTC, epoch from 1970-01-01 UTC +//FILETIME unit (100ns) +#define FILETIME_EPOCH_DIFF 11644473600 // s +time_t FileTime2Epoch(FILETIME filetime) { + uint64_t ll = (((uint64_t)filetime.dwHighDateTime) << 32) | filetime.dwLowDateTime; + ll /= 1e7; // s + return ll - FILETIME_EPOCH_DIFF; +} +#endif + +static bool less(const hdir_t& lhs, const hdir_t& rhs) { + return stricmp(lhs.name, rhs.name) < 0; +} + +int listdir(const char* dir, std::list& dirs) { + int dirlen = strlen(dir); + if (dirlen > 256) { + return -1; + } + char path[512]; + strcpy(path, dir); + if (dir[dirlen-1] != '/') { + strcat(path, "/"); + ++dirlen; + } + dirs.clear(); +#ifdef OS_UNIX + // opendir -> readdir -> closedir + DIR* dp = opendir(dir); + if (dp == NULL) return -1; + struct dirent* result = NULL; + struct stat st; + hdir_t tmp; + while ((result = readdir(dp))) { + memset(&tmp, 0, sizeof(hdir_t)); + strncpy(tmp.name, result->d_name, sizeof(tmp.name)); + strncpy(path+dirlen, result->d_name, sizeof(path)-dirlen); + if (lstat(path, &st) == 0) { + if (S_ISREG(st.st_mode)) tmp.type = 'f'; + else if (S_ISDIR(st.st_mode)) tmp.type = 'd'; + else if (S_ISLNK(st.st_mode)) tmp.type = 'l'; + else if (S_ISBLK(st.st_mode)) tmp.type = 'b'; + else if (S_ISCHR(st.st_mode)) tmp.type = 'c'; + else if (S_ISSOCK(st.st_mode)) tmp.type = 's'; + else if (S_ISFIFO(st.st_mode)) tmp.type = 'p'; + else tmp.type = '-'; + tmp.mode = st.st_mode & 0777; + tmp.size = st.st_size; + tmp.atime = st.st_atime; + tmp.mtime = st.st_mtime; + tmp.ctime = st.st_ctime; + } + dirs.push_back(tmp); + } + closedir(dp); +#elif defined(OS_WIN) + // FindFirstFile -> FindNextFile -> FindClose + strcat(path, "*"); + WIN32_FIND_DATAA data; + HANDLE h = FindFirstFileA(path, &data); + if (h == NULL) { + return -1; + } + hdir_t tmp; + do { + memset(&tmp, 0, sizeof(hdir_t)); + strncpy(tmp.name, data.cFileName, sizeof(tmp.name)); + tmp.type = 'f'; + if (data.dwFileAttributes & _A_SUBDIR) { + tmp.type = 'd'; + } + tmp.mode = 0777; + tmp.size = (((uint64_t)data.nFileSizeHigh) << 32) | data.nFileSizeLow; + tmp.atime = FileTime2Epoch(data.ftLastAccessTime); + tmp.mtime = FileTime2Epoch(data.ftLastWriteTime); + tmp.ctime = FileTime2Epoch(data.ftCreationTime); + dirs.push_back(tmp); + } while (FindNextFileA(h, &data)); + FindClose(h); +#endif + dirs.sort(less); + return dirs.size(); +} diff --git a/external/libhv/libhv-1.3.2/cpputil/hdir.h b/external/libhv/libhv-1.3.2/cpputil/hdir.h new file mode 100644 index 0000000..d570b1b --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hdir.h @@ -0,0 +1,69 @@ +#ifndef HV_DIR_H_ +#define HV_DIR_H_ + +/* + *@code +int main(int argc, char* argv[]) { + const char* dir = "."; + if (argc > 1) { + dir = argv[1]; + } + std::list dirs; + listdir(dir, dirs); + for (auto& item : dirs) { + printf("%c%c%c%c%c%c%c%c%c%c\t", + item.type, + item.mode & 0400 ? 'r' : '-', + item.mode & 0200 ? 'w' : '-', + item.mode & 0100 ? 'x' : '-', + item.mode & 0040 ? 'r' : '-', + item.mode & 0020 ? 'w' : '-', + item.mode & 0010 ? 'x' : '-', + item.mode & 0004 ? 'r' : '-', + item.mode & 0002 ? 'w' : '-', + item.mode & 0001 ? 'x' : '-'); + float hsize; + if (item.size < 1024) { + printf("%lu\t", item.size); + } + else if ((hsize = item.size/1024.0f) < 1024.0f) { + printf("%.1fK\t", hsize); + } + else if ((hsize /= 1024.0f) < 1024.0f) { + printf("%.1fM\t", hsize); + } + else { + hsize /= 1024.0f; + printf("%.1fG\t", hsize); + } + struct tm* tm = localtime(&item.mtime); + printf("%04d-%02d-%02d %02d:%02d:%02d\t", + tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); + printf("%s%s\n", item.name, item.type == 'd' ? "/" : ""); + } + return 0; +} +*/ + +#include +#include + +#include + +#include "hexport.h" + +typedef struct hdir_s { + char name[256]; + char type; // f:file d:dir l:link b:block c:char s:socket p:pipe + char reserverd; + unsigned short mode; + size_t size; + time_t atime; + time_t mtime; + time_t ctime; +} hdir_t; + +// listdir: same as ls on unix, dir on win +HV_EXPORT int listdir(const char* dir, std::list& dirs); + +#endif // HV_DIR_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hfile.h b/external/libhv/libhv-1.3.2/cpputil/hfile.h new file mode 100644 index 0000000..0d681ea --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hfile.h @@ -0,0 +1,134 @@ +#ifndef HV_FILE_H_ +#define HV_FILE_H_ + +#include // for std::string + +#include "hplatform.h" // for stat +#include "hbuf.h" // for HBuf + +class HFile { +public: + HFile() { + filepath[0] = '\0'; + fp = NULL; + } + + ~HFile() { + close(); + } + + int open(const char* filepath, const char* mode) { + close(); + strncpy(this->filepath, filepath, MAX_PATH - 1); + fp = fopen(filepath, mode); + return fp ? 0 : errno; + } + + void close() { + if (fp) { + fclose(fp); + fp = NULL; + } + } + + bool isopen() { + return fp != NULL; + } + + int remove() { + close(); + return ::remove(filepath); + } + + int rename(const char* newpath) { + close(); + return ::rename(filepath, newpath); + } + + size_t read(void* ptr, size_t len) { + return fread(ptr, 1, len, fp); + } + + size_t write(const void* ptr, size_t len) { + return fwrite(ptr, 1, len, fp); + } + + size_t write(const std::string& str) { + return write(str.c_str(), str.length()); + } + + int seek(size_t offset, int whence = SEEK_SET) { + return fseek(fp, offset, whence); + } + + int tell() { + return ftell(fp); + } + + int flush() { + return fflush(fp); + } + + static size_t size(const char* filepath) { + struct stat st; + memset(&st, 0, sizeof(st)); + stat(filepath, &st); + return st.st_size; + } + + size_t size() { + return HFile::size(filepath); + } + + size_t readall(HBuf& buf) { + size_t filesize = size(); + if (filesize == 0) return 0; + buf.resize(filesize); + return fread(buf.base, 1, filesize, fp); + } + + size_t readall(std::string& str) { + size_t filesize = size(); + if (filesize == 0) return 0; + str.resize(filesize); + return fread((void*)str.data(), 1, filesize, fp); + } + + bool readline(std::string& str) { + str.clear(); + char ch; + while (fread(&ch, 1, 1, fp)) { + if (ch == '\n') { + // unix: LF + return true; + } + if (ch == '\r') { + // dos: CRLF + // read LF + if (fread(&ch, 1, 1, fp) && ch != '\n') { + // mac: CR + fseek(fp, -1, SEEK_CUR); + } + return true; + } + str += ch; + } + return str.length() != 0; + } + + int readrange(std::string& str, size_t from = 0, size_t to = 0) { + size_t filesize = size(); + if (filesize == 0) return 0; + if (to == 0 || to >= filesize) to = filesize - 1; + size_t readbytes = to - from + 1; + str.resize(readbytes); + fseek(fp, from, SEEK_SET); + return fread((void*)str.data(), 1, readbytes, fp); + } + +public: + char filepath[MAX_PATH]; + FILE* fp; +}; + +#endif // HV_FILE_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hmap.h b/external/libhv/libhv-1.3.2/cpputil/hmap.h new file mode 100644 index 0000000..1d466d5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hmap.h @@ -0,0 +1,55 @@ +#ifndef HV_MAP_H_ +#define HV_MAP_H_ + +#include "hconfig.h" + +#include +#include + +// MultiMap +namespace std { +/* +int main() { + std::MultiMap kvs; + kvs["name"] = "hw"; + kvs["filename"] = "1.jpg"; + kvs["filename"] = "2.jpg"; + //kvs.insert(std::pair("name", "hw")); + //kvs.insert(std::pair("filename", "1.jpg")); + //kvs.insert(std::pair("filename", "2.jpg")); + for (auto& pair : kvs) { + printf("%s:%s\n", pair.first.c_str(), pair.second.c_str()); + } + auto iter = kvs.find("filename"); + if (iter != kvs.end()) { + for (int i = 0; i < kvs.count("filename"); ++i, ++iter) { + printf("%s:%s\n", iter->first.c_str(), iter->second.c_str()); + } + } + return 0; +} + */ +template +class MultiMap : public multimap { +public: + Value& operator[](Key key) { + auto iter = this->insert(std::pair(key,Value())); + return (*iter).second; + } +}; +} + +#ifdef USE_MULTIMAP +#define HV_MAP std::MultiMap +#else +#define HV_MAP std::map +#endif + +// KeyValue +namespace hv { +typedef std::map keyval_t; +typedef std::MultiMap multi_keyval_t; +typedef HV_MAP KeyValue; +} + +#endif // HV_MAP_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hobjectpool.h b/external/libhv/libhv-1.3.2/cpputil/hobjectpool.h new file mode 100644 index 0000000..31b9f64 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hobjectpool.h @@ -0,0 +1,183 @@ +#ifndef HV_OBJECT_POOL_H_ +#define HV_OBJECT_POOL_H_ + +/* + * @usage unittest/objectpool_test.cpp + */ + +#include +#include +#include +#include + +#define DEFAULT_OBJECT_POOL_INIT_NUM 0 +#define DEFAULT_OBJECT_POOL_MAX_NUM 4 +#define DEFAULT_OBJECT_POOL_TIMEOUT 3000 // ms + +template +class HObjectFactory { +public: + static T* create() { + return new T; + } +}; + +template> +class HObjectPool { +public: + HObjectPool( + int init_num = DEFAULT_OBJECT_POOL_INIT_NUM, + int max_num = DEFAULT_OBJECT_POOL_MAX_NUM, + int timeout = DEFAULT_OBJECT_POOL_TIMEOUT) + : _max_num(max_num) + , _timeout(timeout) + { + for (int i = 0; i < init_num; ++i) { + T* p = TFactory::create(); + if (p) { + objects_.push_back(std::shared_ptr(p)); + } + } + _object_num = objects_.size(); + } + + ~HObjectPool() {} + + int ObjectNum() { return _object_num; } + int IdleNum() { return objects_.size(); } + int BorrowNum() { return ObjectNum() - IdleNum(); } + + std::shared_ptr TryBorrow() { + std::shared_ptr pObj = NULL; + std::lock_guard locker(mutex_); + if (!objects_.empty()) { + pObj = objects_.front(); + objects_.pop_front(); + } + return pObj; + } + + std::shared_ptr Borrow() { + std::shared_ptr pObj = TryBorrow(); + if (pObj) { + return pObj; + } + + std::unique_lock locker(mutex_); + if (_object_num < _max_num) { + ++_object_num; + // NOTE: unlock to avoid TFactory::create block + mutex_.unlock(); + T* p = TFactory::create(); + mutex_.lock(); + if (!p) --_object_num; + return std::shared_ptr(p); + } + + if (_timeout > 0) { + std::cv_status status = cond_.wait_for(locker, std::chrono::milliseconds(_timeout)); + if (status == std::cv_status::timeout) { + return NULL; + } + if (!objects_.empty()) { + pObj = objects_.front(); + objects_.pop_front(); + return pObj; + } + else { + // WARN: No idle object + } + } + return pObj; + } + + void Return(std::shared_ptr& pObj) { + if (!pObj) return; + std::lock_guard locker(mutex_); + objects_.push_back(pObj); + cond_.notify_one(); + } + + bool Add(std::shared_ptr& pObj) { + std::lock_guard locker(mutex_); + if (_object_num >= _max_num) { + return false; + } + objects_.push_back(pObj); + ++_object_num; + cond_.notify_one(); + return true; + } + + bool Remove(std::shared_ptr& pObj) { + std::lock_guard locker(mutex_); + auto iter = objects_.begin(); + while (iter != objects_.end()) { + if (*iter == pObj) { + iter = objects_.erase(iter); + --_object_num; + return true; + } + else { + ++iter; + } + } + return false; + } + + void Clear() { + std::lock_guard locker(mutex_); + objects_.clear(); + _object_num = 0; + } + + int _object_num; + int _max_num; + int _timeout; +private: + std::list> objects_; + std::mutex mutex_; + std::condition_variable cond_; +}; + +template> +class HPoolObject { +public: + typedef HObjectPool PoolType; + + HPoolObject(PoolType& pool) : pool_(pool) + { + sptr_ = pool_.Borrow(); + } + + ~HPoolObject() { + if (sptr_) { + pool_.Return(sptr_); + } + } + + HPoolObject(const HPoolObject&) = delete; + HPoolObject& operator=(const HPoolObject&) = delete; + + T* get() { + return sptr_.get(); + } + + operator bool() { + return sptr_.get() != NULL; + } + + T* operator->() { + return sptr_.get(); + } + + T operator*() { + return *sptr_.get(); + } + +private: + PoolType& pool_; + std::shared_ptr sptr_; +}; + +#endif // HV_OBJECT_POOL_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hpath.cpp b/external/libhv/libhv-1.3.2/cpputil/hpath.cpp new file mode 100644 index 0000000..0a4ffc0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hpath.cpp @@ -0,0 +1,112 @@ +#include "hpath.h" + +#include "hplatform.h" + +bool HPath::exists(const char* path) { + return access(path, 0) == 0; +} + +bool HPath::isdir(const char* path) { + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + stat(path, &st); + return S_ISDIR(st.st_mode); +} + +bool HPath::isfile(const char* path) { + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + stat(path, &st); + return S_ISREG(st.st_mode); +} + +bool HPath::islink(const char* path) { +#ifdef OS_WIN + return HPath::isdir(path) && (GetFileAttributesA(path) & FILE_ATTRIBUTE_REPARSE_POINT); +#else + if (access(path, 0) != 0) return false; + struct stat st; + memset(&st, 0, sizeof(st)); + lstat(path, &st); + return S_ISLNK(st.st_mode); +#endif +} + +std::string HPath::basename(const std::string& filepath) { + std::string::size_type pos1 = filepath.find_last_not_of("/\\"); + if (pos1 == std::string::npos) { + return "/"; + } + std::string::size_type pos2 = filepath.find_last_of("/\\", pos1); + if (pos2 == std::string::npos) { + pos2 = 0; + } else { + pos2++; + } + + return filepath.substr(pos2, pos1-pos2+1); +} + +std::string HPath::dirname(const std::string& filepath) { + std::string::size_type pos1 = filepath.find_last_not_of("/\\"); + if (pos1 == std::string::npos) { + return "/"; + } + std::string::size_type pos2 = filepath.find_last_of("/\\", pos1); + if (pos2 == std::string::npos) { + return "."; + } else if (pos2 == 0) { + pos2 = 1; + } + + return filepath.substr(0, pos2); +} + +std::string HPath::filename(const std::string& filepath) { + std::string::size_type pos1 = filepath.find_last_of("/\\"); + if (pos1 == std::string::npos) { + pos1 = 0; + } else { + pos1++; + } + std::string file = filepath.substr(pos1, -1); + + std::string::size_type pos2 = file.find_last_of("."); + if (pos2 == std::string::npos) { + return file; + } + return file.substr(0, pos2); +} + +std::string HPath::suffixname(const std::string& filepath) { + std::string::size_type pos1 = filepath.find_last_of("/\\"); + if (pos1 == std::string::npos) { + pos1 = 0; + } else { + pos1++; + } + std::string file = filepath.substr(pos1, -1); + + std::string::size_type pos2 = file.find_last_of("."); + if (pos2 == std::string::npos) { + return ""; + } + return file.substr(pos2+1, -1); +} + +std::string HPath::join(const std::string& dir, const std::string& filename) { + char separator = '/'; +#ifdef OS_WIN + if (dir.find_first_of("\\") != std::string::npos) { + separator = '\\'; + } +#endif + std::string filepath(dir); + if (dir[dir.length()-1] != separator) { + filepath += separator; + } + filepath += filename; + return filepath; +} diff --git a/external/libhv/libhv-1.3.2/cpputil/hpath.h b/external/libhv/libhv-1.3.2/cpputil/hpath.h new file mode 100644 index 0000000..28d39e2 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hpath.h @@ -0,0 +1,28 @@ +#ifndef HV_PATH_H_ +#define HV_PATH_H_ + +#include // for std::string + +#include "hexport.h" + +class HV_EXPORT HPath { +public: + static bool exists(const char* path); + static bool isdir(const char* path); + static bool isfile(const char* path); + static bool islink(const char* path); + + // filepath = /mnt/share/image/test.jpg + // basename = test.jpg + // dirname = /mnt/share/image + // filename = test + // suffixname = jpg + static std::string basename(const std::string& filepath); + static std::string dirname(const std::string& filepath); + static std::string filename(const std::string& filepath); + static std::string suffixname(const std::string& filepath); + + static std::string join(const std::string& dir, const std::string& filename); +}; + +#endif // HV_PATH_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hscope.h b/external/libhv/libhv-1.3.2/cpputil/hscope.h new file mode 100644 index 0000000..0222639 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hscope.h @@ -0,0 +1,79 @@ +#ifndef HV_SCOPE_H_ +#define HV_SCOPE_H_ + +#include +typedef std::function Function; + +#include "hdef.h" + +// same as golang defer +class Defer { +public: + Defer(Function&& fn) : _fn(std::move(fn)) {} + ~Defer() { if(_fn) _fn();} +private: + Function _fn; +}; +#define defer(code) Defer STRINGCAT(_defer_, __LINE__)([&](){code}); + +class ScopeCleanup { +public: + template + ScopeCleanup(Fn&& fn, Args&&... args) { + _cleanup = std::bind(std::forward(fn), std::forward(args)...); + } + + ~ScopeCleanup() { + _cleanup(); + } + +private: + Function _cleanup; +}; + +template +class ScopeFree { +public: + ScopeFree(T* p) : _p(p) {} + ~ScopeFree() {SAFE_FREE(_p);} +private: + T* _p; +}; + +template +class ScopeDelete { +public: + ScopeDelete(T* p) : _p(p) {} + ~ScopeDelete() {SAFE_DELETE(_p);} +private: + T* _p; +}; + +template +class ScopeDeleteArray { +public: + ScopeDeleteArray(T* p) : _p(p) {} + ~ScopeDeleteArray() {SAFE_DELETE_ARRAY(_p);} +private: + T* _p; +}; + +template +class ScopeRelease { +public: + ScopeRelease(T* p) : _p(p) {} + ~ScopeRelease() {SAFE_RELEASE(_p);} +private: + T* _p; +}; + +template +class ScopeLock { +public: + ScopeLock(T& mutex) : _mutex(mutex) {_mutex.lock();} + ~ScopeLock() {_mutex.unlock();} +private: + T& _mutex; +}; + +#endif // HV_SCOPE_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hstring.cpp b/external/libhv/libhv-1.3.2/cpputil/hstring.cpp new file mode 100644 index 0000000..d845b36 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hstring.cpp @@ -0,0 +1,205 @@ +#include "hstring.h" + +#include +#include +#include +#include + +namespace hv { + +std::string empty_string; +std::map empty_map; + +std::string& toupper(std::string& str) { + // std::transform(str.begin(), str.end(), str.begin(), ::toupper); + char* p = (char*)str.c_str(); + while (*p != '\0') { + if (*p >= 'a' && *p <= 'z') { + *p &= ~0x20; + } + ++p; + } + return str; +} + +std::string& tolower(std::string& str) { + // std::transform(str.begin(), str.end(), str.begin(), ::tolower); + char* p = (char*)str.c_str(); + while (*p != '\0') { + if (*p >= 'A' && *p <= 'Z') { + *p |= 0x20; + } + ++p; + } + return str; +} + +std::string& reverse(std::string& str) { + // std::reverse(str.begin(), str.end()); + char* b = (char*)str.c_str(); + char* e = b + str.length() - 1; + char tmp; + while (e > b) { + tmp = *e; + *e = *b; + *b = tmp; + --e; + ++b; + } + return str; +} + +bool startswith(const std::string& str, const std::string& start) { + if (str.length() < start.length()) return false; + return str.compare(0, start.length(), start) == 0; +} + +bool endswith(const std::string& str, const std::string& end) { + if (str.length() < end.length()) return false; + return str.compare(str.length() - end.length(), end.length(), end) == 0; +} + +bool contains(const std::string& str, const std::string& sub) { + if (str.length() < sub.length()) return false; + return str.find(sub) != std::string::npos; +} + +static inline int vscprintf(const char* fmt, va_list ap) { + return vsnprintf(NULL, 0, fmt, ap); +} + +std::string asprintf(const char* fmt, ...) { + va_list ap; + va_start(ap, fmt); + int len = vscprintf(fmt, ap); + va_end(ap); + + std::string str; + str.reserve(len+1); + // must resize to set str.size + str.resize(len); + // must recall va_start on unix + va_start(ap, fmt); + vsnprintf((char*)str.data(), len+1, fmt, ap); + va_end(ap); + + return str; +} + +StringList split(const std::string& str, char delim) { + /* + std::stringstream ss; + ss << str; + string item; + StringList res; + while (std::getline(ss, item, delim)) { + res.push_back(item); + } + return res; + */ + const char* p = str.c_str(); + const char* value = p; + StringList res; + while (*p != '\0') { + if (*p == delim) { + res.push_back(std::string(value, p-value)); + value = p+1; + } + ++p; + } + res.push_back(value); + return res; +} + +hv::KeyValue splitKV(const std::string& str, char kv_kv, char k_v) { + enum { + s_key, + s_value, + } state = s_key; + const char* p = str.c_str(); + const char* key = p; + const char* value = NULL; + int key_len = 0; + int value_len = 0; + hv::KeyValue kvs; + while (*p != '\0') { + if (*p == kv_kv) { + if (key_len && value_len) { + kvs[std::string(key, key_len)] = std::string(value, value_len); + key_len = value_len = 0; + } + state = s_key; + key = p+1; + } + else if (*p == k_v) { + state = s_value; + value = p+1; + } + else { + state == s_key ? ++key_len : ++value_len; + } + ++p; + } + if (key_len && value_len) { + kvs[std::string(key, key_len)] = std::string(value, value_len); + } + return kvs; +} + +std::string trim(const std::string& str, const char* chars) { + std::string::size_type pos1 = str.find_first_not_of(chars); + if (pos1 == std::string::npos) return ""; + + std::string::size_type pos2 = str.find_last_not_of(chars); + return str.substr(pos1, pos2-pos1+1); +} + +std::string ltrim(const std::string& str, const char* chars) { + std::string::size_type pos = str.find_first_not_of(chars); + if (pos == std::string::npos) return ""; + return str.substr(pos); +} + +std::string rtrim(const std::string& str, const char* chars) { + std::string::size_type pos = str.find_last_not_of(chars); + return str.substr(0, pos+1); +} + +std::string trim_pairs(const std::string& str, const char* pairs) { + const char* s = str.c_str(); + const char* e = str.c_str() + str.size() - 1; + const char* p = pairs; + bool is_pair = false; + while (*p != '\0' && *(p+1) != '\0') { + if (*s == *p && *e == *(p+1)) { + is_pair = true; + break; + } + p += 2; + } + return is_pair ? str.substr(1, str.size()-2) : str; +} + +std::string replace(const std::string& str, const std::string& find, const std::string& rep) { + std::string res(str); + std::string::size_type pos = res.find(find); + if (pos != std::string::npos) { + res.replace(pos, find.size(), rep); + } + return res; +} + +std::string replaceAll(const std::string& str, const std::string& find, const std::string& rep) { + std::string::size_type pos = 0; + std::string::size_type a = find.size(); + std::string::size_type b = rep.size(); + + std::string res(str); + while ((pos = res.find(find, pos)) != std::string::npos) { + res.replace(pos, a, rep); + pos += b; + } + return res; +} + +} // end namespace hv diff --git a/external/libhv/libhv-1.3.2/cpputil/hstring.h b/external/libhv/libhv-1.3.2/cpputil/hstring.h new file mode 100644 index 0000000..76cf433 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hstring.h @@ -0,0 +1,80 @@ +#ifndef HV_STRING_H_ +#define HV_STRING_H_ + +#include +#include + +#include +#include + +#include "hexport.h" +#include "hplatform.h" +#include "hmap.h" + +#define SPACE_CHARS " \t\r\n" +#define PAIR_CHARS "{}[]()<>\"\"\'\'``" + +namespace hv { + +HV_EXPORT extern std::string empty_string; +HV_EXPORT extern std::map empty_map; + +typedef std::vector StringList; + +// std::map +class StringCaseLess : public std::less { +public: + bool operator()(const std::string& lhs, const std::string& rhs) const { + return strcasecmp(lhs.c_str(), rhs.c_str()) < 0; + } +}; + +// NOTE: low-version NDK not provide std::to_string +template +HV_INLINE std::string to_string(const T& t) { + std::ostringstream oss; + oss << t; + return oss.str(); +} + +template +HV_INLINE T from_string(const std::string& str) { + T t; + std::istringstream iss(str); + iss >> t; + return t; +} + +template +HV_INLINE void print(const T& t) { + std::cout << t; +} + +template +HV_INLINE void println(const T& t) { + std::cout << t << std::endl; +} + +HV_EXPORT std::string& toupper(std::string& str); +HV_EXPORT std::string& tolower(std::string& str); +HV_EXPORT std::string& reverse(std::string& str); + +HV_EXPORT bool startswith(const std::string& str, const std::string& start); +HV_EXPORT bool endswith(const std::string& str, const std::string& end); +HV_EXPORT bool contains(const std::string& str, const std::string& sub); + +HV_EXPORT std::string asprintf(const char* fmt, ...); +// x,y,z +HV_EXPORT StringList split(const std::string& str, char delim = ','); +// k1=v1&k2=v2 +HV_EXPORT hv::KeyValue splitKV(const std::string& str, char kv_kv = '&', char k_v = '='); +HV_EXPORT std::string trim(const std::string& str, const char* chars = SPACE_CHARS); +HV_EXPORT std::string ltrim(const std::string& str, const char* chars = SPACE_CHARS); +HV_EXPORT std::string rtrim(const std::string& str, const char* chars = SPACE_CHARS); +HV_EXPORT std::string trim_pairs(const std::string& str, const char* pairs = PAIR_CHARS); +HV_EXPORT std::string replace(const std::string& str, const std::string& find, const std::string& rep); +HV_EXPORT std::string replaceAll(const std::string& str, const std::string& find, const std::string& rep); + +} // end namespace hv + +#endif // HV_STRING_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hthreadpool.h b/external/libhv/libhv-1.3.2/cpputil/hthreadpool.h new file mode 100644 index 0000000..8df9871 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hthreadpool.h @@ -0,0 +1,249 @@ +#ifndef HV_THREAD_POOL_H_ +#define HV_THREAD_POOL_H_ + +/* + * @usage unittest/threadpool_test.cpp + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEFAULT_THREAD_POOL_MIN_THREAD_NUM 1 +#define DEFAULT_THREAD_POOL_MAX_THREAD_NUM std::thread::hardware_concurrency() +#define DEFAULT_THREAD_POOL_MAX_IDLE_TIME 60000 // ms + +class HThreadPool { +public: + using Task = std::function; + + HThreadPool(int min_threads = DEFAULT_THREAD_POOL_MIN_THREAD_NUM, + int max_threads = DEFAULT_THREAD_POOL_MAX_THREAD_NUM, + int max_idle_ms = DEFAULT_THREAD_POOL_MAX_IDLE_TIME) + : min_thread_num(min_threads) + , max_thread_num(max_threads) + , max_idle_time(max_idle_ms) + , status(STOP) + , cur_thread_num(0) + , idle_thread_num(0) + {} + + virtual ~HThreadPool() { + stop(); + } + + void setMinThreadNum(int min_threads) { + min_thread_num = min_threads; + } + void setMaxThreadNum(int max_threads) { + max_thread_num = max_threads; + } + void setMaxIdleTime(int ms) { + max_idle_time = ms; + } + int currentThreadNum() { + return cur_thread_num; + } + int idleThreadNum() { + return idle_thread_num; + } + size_t taskNum() { + std::lock_guard locker(task_mutex); + return tasks.size(); + } + bool isStarted() { + return status != STOP; + } + bool isStopped() { + return status == STOP; + } + + int start(int start_threads = 0) { + if (status != STOP) return -1; + status = RUNNING; + if (start_threads < min_thread_num) start_threads = min_thread_num; + if (start_threads > max_thread_num) start_threads = max_thread_num; + for (int i = 0; i < start_threads; ++i) { + createThread(); + } + return 0; + } + + int stop() { + if (status == STOP) return -1; + status = STOP; + task_cond.notify_all(); + for (auto& i : threads) { + if (i.thread->joinable()) { + i.thread->join(); + } + } + threads.clear(); + cur_thread_num = 0; + idle_thread_num = 0; + return 0; + } + + int pause() { + if (status == RUNNING) { + status = PAUSE; + } + return 0; + } + + int resume() { + if (status == PAUSE) { + status = RUNNING; + } + return 0; + } + + int wait() { + while (status != STOP) { + if (tasks.empty() && idle_thread_num == cur_thread_num) { + break; + } + std::this_thread::yield(); + } + return 0; + } + + /* + * return a future, calling future.get() will wait task done and return RetType. + * commit(fn, args...) + * commit(std::bind(&Class::mem_fn, &obj)) + * commit(std::mem_fn(&Class::mem_fn, &obj)) + * + */ + template + auto commit(Fn&& fn, Args&&... args) -> std::future { + if (status == STOP) start(); + if (idle_thread_num <= tasks.size() && cur_thread_num < max_thread_num) { + createThread(); + } + using RetType = decltype(fn(args...)); + auto task = std::make_shared >( + std::bind(std::forward(fn), std::forward(args)...)); + std::future future = task->get_future(); + { + std::lock_guard locker(task_mutex); + tasks.emplace([task]{ + (*task)(); + }); + } + + task_cond.notify_one(); + return future; + } + +protected: + bool createThread() { + if (cur_thread_num >= max_thread_num) return false; + std::thread* thread = new std::thread([this] { + while (status != STOP) { + while (status == PAUSE) { + std::this_thread::yield(); + } + + Task task; + { + std::unique_lock locker(task_mutex); + task_cond.wait_for(locker, std::chrono::milliseconds(max_idle_time), [this]() { + return status == STOP || !tasks.empty(); + }); + if (status == STOP) return; + if (tasks.empty()) { + if (cur_thread_num > min_thread_num) { + delThread(std::this_thread::get_id()); + return; + } + continue; + } + --idle_thread_num; + task = std::move(tasks.front()); + tasks.pop(); + } + if (task) { + task(); + ++idle_thread_num; + } + } + }); + addThread(thread); + return true; + } + + void addThread(std::thread* thread) { + thread_mutex.lock(); + ++cur_thread_num; + ++idle_thread_num; + ThreadData data; + data.thread = std::shared_ptr(thread); + data.id = thread->get_id(); + data.status = RUNNING; + data.start_time = time(NULL); + data.stop_time = 0; + threads.emplace_back(data); + thread_mutex.unlock(); + } + + void delThread(std::thread::id id) { + time_t now = time(NULL); + thread_mutex.lock(); + --cur_thread_num; + --idle_thread_num; + auto iter = threads.begin(); + while (iter != threads.end()) { + if (iter->status == STOP && now > iter->stop_time) { + if (iter->thread->joinable()) { + iter->thread->join(); + iter = threads.erase(iter); + continue; + } + } else if (iter->id == id) { + iter->status = STOP; + iter->stop_time = time(NULL); + } + ++iter; + } + thread_mutex.unlock(); + } + +public: + int min_thread_num; + int max_thread_num; + int max_idle_time; + +protected: + enum Status { + STOP, + RUNNING, + PAUSE, + }; + struct ThreadData { + std::shared_ptr thread; + std::thread::id id; + Status status; + time_t start_time; + time_t stop_time; + }; + std::atomic status; + std::atomic cur_thread_num; + std::atomic idle_thread_num; + std::list threads; + std::mutex thread_mutex; + std::queue tasks; + std::mutex task_mutex; + std::condition_variable task_cond; +}; + +#endif // HV_THREAD_POOL_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/hurl.cpp b/external/libhv/libhv-1.3.2/cpputil/hurl.cpp new file mode 100644 index 0000000..7556308 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hurl.cpp @@ -0,0 +1,184 @@ +#include "hurl.h" + +#include "hdef.h" +#include "hbase.h" + +/* +static bool Curl_isunreserved(unsigned char in) +{ + switch(in) { + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': + case '-': case '.': case '_': case '~': + return TRUE; + default: + break; + } + return FLASE; +} +*/ + +static inline bool is_unambiguous(char c) { + return IS_ALPHANUM(c) || + c == '-' || + c == '_' || + c == '.' || + c == '~'; +} + +static inline bool char_in_str(char c, const char* str) { + const char* p = str; + while (*p && *p != c) ++p; + return *p != '\0'; +} + +static inline unsigned char hex2i(char hex) { + return hex <= '9' ? hex - '0' : + hex <= 'F' ? hex - 'A' + 10 : hex - 'a' + 10; +} + +std::string HUrl::escape(const std::string& str, const char* unescaped_chars) { + std::string ostr; + static char tab[] = "0123456789ABCDEF"; + const unsigned char* p = reinterpret_cast(str.c_str()); + char szHex[4] = "%00"; + while (*p != '\0') { + if (is_unambiguous(*p) || char_in_str(*p, unescaped_chars)) { + ostr += *p; + } + else { + szHex[1] = tab[*p >> 4]; + szHex[2] = tab[*p & 0xF]; + ostr += szHex; + } + ++p; + } + return ostr; +} + +std::string HUrl::unescape(const std::string& str) { + std::string ostr; + const char* p = str.c_str(); + while (*p != '\0') { + if (*p == '%' && + IS_HEX(p[1]) && + IS_HEX(p[2])) { + ostr += ((hex2i(p[1]) << 4) | hex2i(p[2])); + p += 3; + } + else { + if (*p == '+') { + ostr += ' '; + } else { + ostr += *p; + } + ++p; + } + } + return ostr; +} + +void HUrl::reset() { + url.clear(); + scheme.clear(); + username.clear(); + password.clear(); + host.clear(); + port = 0; + path.clear(); + query.clear(); + fragment.clear(); +} + +bool HUrl::parse(const std::string& url) { + reset(); + this->url = url; + hurl_t stURL; + if (hv_parse_url(&stURL, url.c_str()) != 0) { + return false; + } + int len = stURL.fields[HV_URL_SCHEME].len; + if (len > 0) { + scheme = url.substr(stURL.fields[HV_URL_SCHEME].off, len); + } + len = stURL.fields[HV_URL_USERNAME].len; + if (len > 0) { + username = url.substr(stURL.fields[HV_URL_USERNAME].off, len); + len = stURL.fields[HV_URL_PASSWORD].len; + if (len > 0) { + password = url.substr(stURL.fields[HV_URL_PASSWORD].off, len); + } + } + len = stURL.fields[HV_URL_HOST].len; + if (len > 0) { + host = url.substr(stURL.fields[HV_URL_HOST].off, len); + } + port = stURL.port; + len = stURL.fields[HV_URL_PATH].len; + if (len > 0) { + path = url.substr(stURL.fields[HV_URL_PATH].off, len); + } else { + path = "/"; + } + len = stURL.fields[HV_URL_QUERY].len; + if (len > 0) { + query = url.substr(stURL.fields[HV_URL_QUERY].off, len); + } + len = stURL.fields[HV_URL_FRAGMENT].len; + if (len > 0) { + fragment = url.substr(stURL.fields[HV_URL_FRAGMENT].off, len); + } + return true; +} + +const std::string& HUrl::dump() { + url.clear(); + // scheme:// + if (!scheme.empty()) { + url += scheme; + url += "://"; + } + // user:pswd@ + if (!username.empty()) { + url += username; + if (!password.empty()) { + url += ":"; + url += password; + } + url += "@"; + } + // host:port + if (!host.empty()) { + url += host; + if (port != 80 && port != 443) { + char buf[16] = {0}; + snprintf(buf, sizeof(buf), ":%d", port); + url += port; + } + } + // /path + if (!path.empty()) { + url += path; + } + // ?query + if (!query.empty()) { + url += '?'; + url += query; + } + // #fragment + if (!fragment.empty()) { + url += '#'; + url += fragment; + } + return url; +} diff --git a/external/libhv/libhv-1.3.2/cpputil/hurl.h b/external/libhv/libhv-1.3.2/cpputil/hurl.h new file mode 100644 index 0000000..70fbdda --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/hurl.h @@ -0,0 +1,34 @@ +#ifndef HV_URL_H_ +#define HV_URL_H_ + +#include // import std::string + +#include "hexport.h" + +class HV_EXPORT HUrl { +public: + static std::string escape(const std::string& str, const char* unescaped_chars = ""); + static std::string unescape(const std::string& str); + static inline std::string escapeUrl(const std::string& url) { + return escape(url, ":/@?=&#+"); + } + + HUrl() : port(0) {} + ~HUrl() {} + + void reset(); + bool parse(const std::string& url); + const std::string& dump(); + + std::string url; + std::string scheme; + std::string username; + std::string password; + std::string host; + int port; + std::string path; + std::string query; + std::string fragment; +}; + +#endif // HV_URL_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/ifconfig.cpp b/external/libhv/libhv-1.3.2/cpputil/ifconfig.cpp new file mode 100644 index 0000000..b7107d8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/ifconfig.cpp @@ -0,0 +1,223 @@ +#include "ifconfig.h" + +#include "hplatform.h" + +#ifdef OS_LINUX +#include +#include +#include +#include +#include +#include +#include + +int ifconfig(std::vector& ifcs) { + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock < 0) { + return -10; + } + + struct ifconf ifc; + char buf[1024]; + ifc.ifc_len = sizeof(buf); + ifc.ifc_buf = buf; + + int iRet = ioctl(sock, SIOCGIFCONF, &ifc); + if (iRet != 0) { + close(sock); + return iRet; + } + + int cnt = ifc.ifc_len / sizeof(struct ifreq); + //printf("ifc.size=%d\n", cnt); + if (cnt == 0) { + close(sock); + return -20; + } + + struct ifreq ifr; + ifcs.clear(); + ifconfig_t tmp; + for (int i = 0; i < cnt; ++i) { + // name + strcpy(ifr.ifr_name, ifc.ifc_req[i].ifr_name); + //printf("name: %s\n", ifr.ifr_name); + strncpy(tmp.name, ifr.ifr_name, sizeof(tmp.name)); + // flags + //iRet = ioctl(sock, SIOCGIFFLAGS, &ifr); + //short flags = ifr.ifr_flags; + // addr + iRet = ioctl(sock, SIOCGIFADDR, &ifr); + struct sockaddr_in* addr = (struct sockaddr_in*)&ifr.ifr_addr; + char* ip = inet_ntoa(addr->sin_addr); + //printf("ip: %s\n", ip); + strncpy(tmp.ip, ip, sizeof(tmp.ip)); + // netmask + iRet = ioctl(sock, SIOCGIFNETMASK, &ifr); + addr = (struct sockaddr_in*)&ifr.ifr_netmask; + char* netmask = inet_ntoa(addr->sin_addr); + //printf("netmask: %s\n", netmask); + strncpy(tmp.mask, netmask, sizeof(tmp.mask)); + // broadaddr + iRet = ioctl(sock, SIOCGIFBRDADDR, &ifr); + addr = (struct sockaddr_in*)&ifr.ifr_broadaddr; + char* broadaddr = inet_ntoa(addr->sin_addr); + //printf("broadaddr: %s\n", broadaddr); + strncpy(tmp.broadcast, broadaddr, sizeof(tmp.broadcast)); + // hwaddr + iRet = ioctl(sock, SIOCGIFHWADDR, &ifr); + snprintf(tmp.mac, sizeof(tmp.mac), "%02x:%02x:%02x:%02x:%02x:%02x", + (unsigned char)ifr.ifr_hwaddr.sa_data[0], + (unsigned char)ifr.ifr_hwaddr.sa_data[1], + (unsigned char)ifr.ifr_hwaddr.sa_data[2], + (unsigned char)ifr.ifr_hwaddr.sa_data[3], + (unsigned char)ifr.ifr_hwaddr.sa_data[4], + (unsigned char)ifr.ifr_hwaddr.sa_data[5]); + //printf("mac: %s\n", tmp.mac); + //printf("\n"); + + if (strcmp(tmp.ip, "0.0.0.0") == 0 || + strcmp(tmp.ip, "127.0.0.1") == 0 || + strcmp(tmp.mac, "00:00:00:00:00:00") == 0) { + continue; + } + + ifcs.push_back(tmp); + } + + close(sock); + return 0; +} +#elif defined(OS_WIN) +#include +#include +#include +#include +int ifconfig(std::vector& ifcs) { + PIP_ADAPTER_ADDRESSES pAddrs = NULL; + ULONG buflen = 0; + GetAdaptersAddresses(AF_INET, 0, NULL, pAddrs, &buflen); + pAddrs = (PIP_ADAPTER_ADDRESSES)malloc(buflen); + GetAdaptersAddresses(AF_INET, 0, NULL, pAddrs, &buflen); + + PIP_ADAPTER_INFO pInfos = NULL; + buflen = 0; + GetAdaptersInfo(pInfos, &buflen); + pInfos = (PIP_ADAPTER_INFO)malloc(buflen); + GetAdaptersInfo(pInfos, &buflen); + + ifconfig_t ifc; + std::vector tmp_ifcs; + PIP_ADAPTER_ADDRESSES pAddr = pAddrs; + char mac[32] = {'\0'}; + while (pAddr) { + snprintf(mac, sizeof(mac), "%02x:%02x:%02x:%02x:%02x:%02x", + pAddr->PhysicalAddress[0], + pAddr->PhysicalAddress[1], + pAddr->PhysicalAddress[2], + pAddr->PhysicalAddress[3], + pAddr->PhysicalAddress[4], + pAddr->PhysicalAddress[5]); + + memset(&ifc, 0, sizeof(ifc)); + strncpy(ifc.name, pAddr->AdapterName, sizeof(ifc.name)); + strncpy(ifc.ip, "0.0.0.0", sizeof(ifc.ip)); + strncpy(ifc.mask, "255.255.255.255", sizeof(ifc.mask)); + strncpy(ifc.mac, mac, sizeof(ifc.mac)); + tmp_ifcs.push_back(ifc); + + pAddr = pAddr->Next; + } + + PIP_ADAPTER_INFO pInfo = pInfos; + while (pInfo) { + for (auto& item : tmp_ifcs) { + if (strcmp(item.name, pInfo->AdapterName) == 0) { + // description more friendly + strncpy(item.name, pInfo->Description, sizeof(item.name)); + strncpy(item.ip, pInfo->IpAddressList.IpAddress.String, sizeof(item.ip)); + strncpy(item.mask, pInfo->IpAddressList.IpMask.String, sizeof(item.mask)); + } + } + + pInfo = pInfo->Next; + } + + free(pAddrs); + free(pInfos); + + // filter + ifcs.clear(); + for (auto& item : tmp_ifcs) { + if (strcmp(item.ip, "0.0.0.0") == 0 || + strcmp(item.ip, "127.0.0.1") == 0 || + strcmp(item.mac, "00:00:00:00:00:00") == 0) { + continue; + } + ifcs.push_back(item); + } + + return 0; +} +#elif defined(OS_MAC) +#include +#include +int ifconfig(std::vector& ifcs) { + struct ifaddrs *ifas, *ifap; + int ret = getifaddrs(&ifas); + if (ret != 0) return ret; + ifconfig_s tmp; + for (ifap = ifas; ifap != NULL; ifap = ifap->ifa_next) { + if (ifap->ifa_addr->sa_family == AF_INET) { + // ipv4 + struct sockaddr_in* addr = (struct sockaddr_in*)ifap->ifa_addr; + char* ip = inet_ntoa(addr->sin_addr); + // filter + if (strcmp(ip, "0.0.0.0") == 0 || strcmp(ip, "127.0.0.1") == 0) { + continue; + } + memset(&tmp, 0, sizeof(tmp)); + strncpy(tmp.name, ifap->ifa_name, sizeof(tmp.name)); + strncpy(tmp.ip, ip, sizeof(tmp.ip)); + // netmask + addr = (struct sockaddr_in*)ifap->ifa_netmask; + char* netmask = inet_ntoa(addr->sin_addr); + strncpy(tmp.mask, netmask, sizeof(tmp.mask)); + // broadaddr + addr = (struct sockaddr_in*)ifap->ifa_broadaddr; + char* broadaddr = inet_ntoa(addr->sin_addr); + strncpy(tmp.broadcast, broadaddr, sizeof(tmp.broadcast)); + // push_back + ifcs.push_back(tmp); + } + } + + for (ifap = ifas; ifap != NULL; ifap = ifap->ifa_next) { + if (ifap->ifa_addr->sa_family == AF_LINK) { + // hwaddr + for (auto iter = ifcs.begin(); iter != ifcs.end(); ++iter) { + if (strcmp(iter->name, ifap->ifa_name) == 0) { + struct sockaddr_dl* addr = (struct sockaddr_dl*)ifap->ifa_addr; + unsigned char* pmac = (unsigned char*)LLADDR(addr); + snprintf(iter->mac, sizeof(iter->mac), "%02x:%02x:%02x:%02x:%02x:%02x", + pmac[0], pmac[1], pmac[2], pmac[3], pmac[4], pmac[5]); + // filter + if (strcmp(iter->mac, "00:00:00:00:00:00") == 0) { + ifcs.erase(iter); + } + break; + } + } + } + } + + freeifaddrs(ifas); + return 0; +} + +#else +int ifconfig(std::vector& ifcs) { + return -10; // unimplemented +} +#endif + diff --git a/external/libhv/libhv-1.3.2/cpputil/ifconfig.h b/external/libhv/libhv-1.3.2/cpputil/ifconfig.h new file mode 100644 index 0000000..cf717d0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/ifconfig.h @@ -0,0 +1,36 @@ +#ifndef HV_IFCONFIG_H_ +#define HV_IFCONFIG_H_ + +#include + +#include "hexport.h" + +#ifdef _MSC_VER +#pragma comment(lib, "iphlpapi.lib") +#pragma comment(lib, "ws2_32.lib") +#endif + +typedef struct ifconfig_s { + char name[128]; + char ip[16]; + char mask[16]; + char broadcast[16]; + char mac[20]; +} ifconfig_t; + +/* + * @test + std::vector ifcs; + ifconfig(ifcs); + for (auto& item : ifcs) { + printf("%s\nip: %s\nmask: %s\nbroadcast: %s\nmac: %s\n\n", + item.name, + item.ip, + item.mask, + item.broadcast, + item.mac); + } + */ +HV_EXPORT int ifconfig(std::vector& ifcs); + +#endif // HV_IFCONFIG_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/iniparser.cpp b/external/libhv/libhv-1.3.2/cpputil/iniparser.cpp new file mode 100644 index 0000000..86df999 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/iniparser.cpp @@ -0,0 +1,390 @@ +#include "iniparser.h" + +#include + +#include "hdef.h" +#include "herr.h" +#include "hstring.h" +#include "hfile.h" +#include "hbase.h" + +using namespace hv; + +/********************************** +# div + +[section] + +key = value # span + +# div +***********************************/ + +class IniNode { +public: + enum Type { + INI_NODE_TYPE_UNKNOWN, + INI_NODE_TYPE_ROOT, + INI_NODE_TYPE_SECTION, + INI_NODE_TYPE_KEY_VALUE, + INI_NODE_TYPE_DIV, + INI_NODE_TYPE_SPAN, + } type; + std::string label; // section|key|comment + std::string value; + std::list children; + + virtual ~IniNode() { + for (auto pNode : children) { + if (pNode) { + delete pNode; + } + } + children.clear(); + } + + void Add(IniNode* pNode) { + children.push_back(pNode); + } + + void Del(IniNode* pNode) { + for (auto iter = children.begin(); iter != children.end(); ++iter) { + if ((*iter) == pNode) { + delete (*iter); + children.erase(iter); + return; + } + } + } + + IniNode* Get(const std::string& label, Type type = INI_NODE_TYPE_KEY_VALUE) { + for (auto pNode : children) { + if (pNode->type == type && pNode->label == label) { + return pNode; + } + } + return NULL; + } +}; + +class IniSection : public IniNode { +public: + IniSection() : IniNode(), section(label) { + type = INI_NODE_TYPE_SECTION; + } + std::string §ion; +}; + +class IniKeyValue : public IniNode { +public: + IniKeyValue() : IniNode(), key(label) { + type = INI_NODE_TYPE_KEY_VALUE; + } + std::string &key; +}; + +class IniComment : public IniNode { +public: + IniComment() : IniNode(), comment(label) { + } + std::string &comment; +}; + +IniParser::IniParser() { + _comment = DEFAULT_INI_COMMENT; + _delim = DEFAULT_INI_DELIM; + root_ = NULL; +} + +IniParser::~IniParser() { + Unload(); +} + +int IniParser::Unload() { + SAFE_DELETE(root_); + return 0; +} + +int IniParser::Reload() { + return LoadFromFile(_filepath.c_str()); +} + +int IniParser::LoadFromFile(const char* filepath) { + _filepath = filepath; + + HFile file; + if (file.open(filepath, "r") != 0) { + return ERR_OPEN_FILE; + } + + std::string str; + file.readall(str); + const char* c_str = str.c_str(); + unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF }; + if (str.size() >= 3 && memcmp(c_str, utf8_bom, 3) == 0) { + c_str += 3; + } + return LoadFromMem(c_str); +} + +int IniParser::LoadFromMem(const char* data) { + Unload(); + + root_ = new IniNode; + root_->type = IniNode::INI_NODE_TYPE_ROOT; + + std::stringstream ss; + ss << data; + std::string strLine; + int line = 0; + std::string::size_type pos; + + std::string content, comment, strDiv; + IniNode* pScopeNode = root_; + IniNode* pNewNode = NULL; + while (std::getline(ss, strLine)) { + ++line; + + content = ltrim(strLine); + if (content.length() == 0) { + // blank line + strDiv += '\n'; + continue; + } + + // trim_comment + comment = ""; + pos = content.find_first_of(_comment); + if (pos != std::string::npos) { + comment = content.substr(pos); + content = content.substr(0, pos); + } + + content = rtrim(content); + if (content.length() == 0) { + strDiv += strLine; + strDiv += '\n'; + continue; + } else if (strDiv.length() != 0) { + IniNode* pNode = new IniNode; + pNode->type = IniNode::INI_NODE_TYPE_DIV; + pNode->label = strDiv; + pScopeNode->Add(pNode); + strDiv = ""; + } + + if (content[0] == '[') { + if (content[content.length()-1] == ']') { + // section + content = trim(content.substr(1, content.length()-2)); + pNewNode = new IniNode; + pNewNode->type = IniNode::INI_NODE_TYPE_SECTION; + pNewNode->label = content; + root_->Add(pNewNode); + pScopeNode = pNewNode; + } else { + // hlogw("format error, line:%d", line); + continue; // ignore + } + } else { + pos = content.find_first_of(_delim); + if (pos != std::string::npos) { + // key-value + pNewNode = new IniNode; + pNewNode->type = IniNode::INI_NODE_TYPE_KEY_VALUE; + pNewNode->label = trim(content.substr(0, pos)); + pNewNode->value = trim(content.substr(pos+_delim.length())); + pScopeNode->Add(pNewNode); + } else { + // hlogw("format error, line:%d", line); + continue; // ignore + } + } + + if (comment.length() != 0) { + // tail_comment + IniNode* pNode = new IniNode; + pNode->type = IniNode::INI_NODE_TYPE_SPAN; + pNode->label = comment; + pNewNode->Add(pNode); + comment = ""; + } + } + + // file end comment + if (strDiv.length() != 0) { + IniNode* pNode = new IniNode; + pNode->type = IniNode::INI_NODE_TYPE_DIV; + pNode->label = strDiv; + root_->Add(pNode); + } + + return 0; +} + +void IniParser::DumpString(IniNode* pNode, std::string& str) { + if (pNode == NULL) return; + + if (pNode->type != IniNode::INI_NODE_TYPE_SPAN) { + if (str.length() > 0 && str[str.length()-1] != '\n') { + str += '\n'; + } + } + + switch (pNode->type) { + case IniNode::INI_NODE_TYPE_SECTION: { + str += '['; + str += pNode->label; + str += ']'; + } + break; + case IniNode::INI_NODE_TYPE_KEY_VALUE: { + str += asprintf("%s %s %s", pNode->label.c_str(), _delim.c_str(), pNode->value.c_str()); + } + break; + case IniNode::INI_NODE_TYPE_DIV: { + str += pNode->label; + } + break; + case IniNode::INI_NODE_TYPE_SPAN: { + str += '\t'; + str += pNode->label; + } + break; + default: + break; + } + + for (auto p : pNode->children) { + DumpString(p, str); + } +} + +std::string IniParser::DumpString() { + std::string str; + DumpString(root_, str); + return str; +} + +int IniParser::Save() { + return SaveAs(_filepath.c_str()); +} + +int IniParser::SaveAs(const char* filepath) { + std::string str = DumpString(); + if (str.length() == 0) { + return 0; + } + + HFile file; + if (file.open(filepath, "w") != 0) { + return ERR_SAVE_FILE; + } + file.write(str.c_str(), str.length()); + + return 0; +} + +std::list IniParser::GetSections() { + std::list ret; + if (root_ == NULL) return std::move(ret); + + for (auto pNode : root_->children) { + if (pNode->type == IniNode::INI_NODE_TYPE_SECTION) { + ret.push_back(pNode->label); + } + } + return std::move(ret); +} + +std::list IniParser::GetKeys(const std::string& section) { + std::list ret; + if (root_ == NULL) return std::move(ret); + + IniNode* pSection = root_; + if (section.length() != 0) { + pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); + if (pSection == NULL) return std::move(ret); + } + + for (auto pNode : pSection->children) { + if (pNode->type == IniNode::INI_NODE_TYPE_KEY_VALUE) { + ret.push_back(pNode->label); + } + } + return std::move(ret); +} + +std::string IniParser::GetValue(const std::string& key, const std::string& section) { + if (root_ == NULL) return ""; + + IniNode* pSection = root_; + if (section.length() != 0) { + pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); + if (pSection == NULL) return ""; + } + + IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE); + if (pKV == NULL) return ""; + + return pKV->value; +} + +void IniParser::SetValue(const std::string& key, const std::string& value, const std::string& section) { + if (root_ == NULL) { + root_ = new IniNode; + } + + IniNode* pSection = root_; + if (section.length() != 0) { + pSection = root_->Get(section, IniNode::INI_NODE_TYPE_SECTION); + if (pSection == NULL) { + pSection = new IniNode; + pSection->type = IniNode::INI_NODE_TYPE_SECTION; + pSection->label = section; + root_->Add(pSection); + } + } + + IniNode* pKV = pSection->Get(key, IniNode::INI_NODE_TYPE_KEY_VALUE); + if (pKV == NULL) { + pKV = new IniNode; + pKV->type = IniNode::INI_NODE_TYPE_KEY_VALUE; + pKV->label = key; + pSection->Add(pKV); + } + pKV->value = value; +} + +template<> +HV_EXPORT bool IniParser::Get(const std::string& key, const std::string& section, bool defvalue) { + std::string str = GetValue(key, section); + return str.empty() ? defvalue : hv_getboolean(str.c_str()); +} + +template<> +HV_EXPORT int IniParser::Get(const std::string& key, const std::string& section, int defvalue) { + std::string str = GetValue(key, section); + return str.empty() ? defvalue : atoi(str.c_str()); +} + +template<> +HV_EXPORT float IniParser::Get(const std::string& key, const std::string& section, float defvalue) { + std::string str = GetValue(key, section); + return str.empty() ? defvalue : atof(str.c_str()); +} + +template<> +HV_EXPORT void IniParser::Set(const std::string& key, const bool& value, const std::string& section) { + SetValue(key, value ? "true" : "false", section); +} + +template<> +HV_EXPORT void IniParser::Set(const std::string& key, const int& value, const std::string& section) { + SetValue(key, asprintf("%d", value), section); +} + +template<> +HV_EXPORT void IniParser::Set(const std::string& key, const float& value, const std::string& section) { + SetValue(key, asprintf("%f", value), section); +} diff --git a/external/libhv/libhv-1.3.2/cpputil/iniparser.h b/external/libhv/libhv-1.3.2/cpputil/iniparser.h new file mode 100644 index 0000000..747a96a --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/iniparser.h @@ -0,0 +1,53 @@ +#ifndef HV_INI_PARSER_H_ +#define HV_INI_PARSER_H_ + +#include +#include + +#include "hexport.h" + +#define DEFAULT_INI_COMMENT "#" +#define DEFAULT_INI_DELIM "=" + +// fwd +class IniNode; + +class HV_EXPORT IniParser { +public: + IniParser(); + ~IniParser(); + + int LoadFromFile(const char* filepath); + int LoadFromMem(const char* data); + int Unload(); + int Reload(); + + std::string DumpString(); + int Save(); + int SaveAs(const char* filepath); + + std::list GetSections(); + std::list GetKeys(const std::string& section = ""); + std::string GetValue(const std::string& key, const std::string& section = ""); + void SetValue(const std::string& key, const std::string& value, const std::string& section = ""); + + // T = [bool, int, float] + template + T Get(const std::string& key, const std::string& section = "", T defvalue = 0); + + // T = [bool, int, float] + template + void Set(const std::string& key, const T& value, const std::string& section = ""); + +protected: + void DumpString(IniNode* pNode, std::string& str); + +public: + std::string _comment; + std::string _delim; + std::string _filepath; +private: + IniNode* root_; +}; + +#endif // HV_INI_PARSER_H_ diff --git a/external/libhv/libhv-1.3.2/cpputil/json.hpp b/external/libhv/libhv-1.3.2/cpputil/json.hpp new file mode 100644 index 0000000..a70aaf8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/json.hpp @@ -0,0 +1,25447 @@ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.9.1 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2019 Niels Lohmann . + +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. +*/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 9 +#define NLOHMANN_JSON_VERSION_PATCH 1 + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#include // istream, ostream +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include + +// #include + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // pair +// #include +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to + * the public domain worldwide. This software is distributed without + * any warranty. + * + * For details, see . + * SPDX-License-Identifier: CC0-1.0 + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 13) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 13 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(_MSC_VER) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(VER / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) __has_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP \ +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(14, 0, 0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + JSON_HEDLEY_HAS_FEATURE(c_static_assert) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +#if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 +#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 +#endif + +// disable float-equal warnings on GCC/clang +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdocumentation" +#endif + +// allow to disable exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow to override assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/*! +@brief general exception of the @ref basic_json class + +This class is an extension of `std::exception` objects with a member @a id for +exception ids. It is used as the base class for all exceptions thrown by the +@ref basic_json class. This class can hence be used as "wildcard" to catch +exceptions. + +Subclasses: +- @ref parse_error for exceptions indicating a parse error +- @ref invalid_iterator for exceptions indicating errors with iterators +- @ref type_error for exceptions indicating executing a member function with + a wrong type +- @ref out_of_range for exceptions indicating access out of the defined range +- @ref other_error for exceptions indicating other library errors + +@internal +@note To have nothrow-copy-constructible exceptions, we internally use + `std::runtime_error` which can cope with arbitrary-length error messages. + Intermediate strings are built with static functions and then passed to + the actual constructor. +@endinternal + +@liveexample{The following code shows how arbitrary library exceptions can be +caught.,exception} + +@since version 3.0.0 +*/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + JSON_HEDLEY_RETURNS_NON_NULL + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; + + protected: + JSON_HEDLEY_NON_NULL(3) + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/*! +@brief exception indicating a parse error + +This exception is thrown by the library when a parse error occurs. Parse errors +can occur during the deserialization of JSON text, CBOR, MessagePack, as well +as when using JSON Patch. + +Member @a byte holds the byte index of the last read character in the input +file. + +Exceptions have ids 1xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. +json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. +json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. +json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. +json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. +json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. +json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. +json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. +json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. +json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. +json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. +json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. +json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). +json.exception.parse_error.115 | parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A | A UBJSON high-precision number could not be parsed. + +@note For an input with n bytes, 1 is the index of the first character and n+1 + is the index of the terminating null byte or the end of file. This also + holds true when reading a byte vector (CBOR or MessagePack). + +@liveexample{The following code shows how a `parse_error` exception can be +caught.,parse_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + static parse_error create(int id_, const position_t& pos, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + what_arg; + return parse_error(id_, pos.chars_read_total, w.c_str()); + } + + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + what_arg; + return parse_error(id_, byte_, w.c_str()); + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/*! +@brief exception indicating errors with iterators + +This exception is thrown if iterators passed to a library function do not match +the expected semantics. + +Exceptions have ids 2xx. + +name / id | example message | description +----------------------------------- | --------------- | ------------------------- +json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. +json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. +json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. +json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. +json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. +json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. +json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. +json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. +json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. +json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. +json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. +json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). + +@liveexample{The following code shows how an `invalid_iterator` exception can be +caught.,invalid_iterator} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class invalid_iterator : public exception +{ + public: + static invalid_iterator create(int id_, const std::string& what_arg) + { + std::string w = exception::name("invalid_iterator", id_) + what_arg; + return invalid_iterator(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating executing a member function with a wrong type + +This exception is thrown in case of a type error; that is, a library function is +executed on a JSON value whose type does not match the expected semantics. + +Exceptions have ids 3xx. + +name / id | example message | description +----------------------------- | --------------- | ------------------------- +json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. +json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. +json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t &. +json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. +json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. +json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. +json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. +json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. +json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. +json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. +json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. +json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. +json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. +json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. +json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. +json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | +json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | + +@liveexample{The following code shows how a `type_error` exception can be +caught.,type_error} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref out_of_range for exceptions indicating access out of the defined range +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class type_error : public exception +{ + public: + static type_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("type_error", id_) + what_arg; + return type_error(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating access out of the defined range + +This exception is thrown in case a library function is called on an input +parameter that exceeds the expected range, for instance in case of array +indices or nonexisting object keys. + +Exceptions have ids 4xx. + +name / id | example message | description +------------------------------- | --------------- | ------------------------- +json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. +json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. +json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. +json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. +json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. +json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. +json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. (until version 3.8.0) | +json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | +json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | + +@liveexample{The following code shows how an `out_of_range` exception can be +caught.,out_of_range} + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref other_error for exceptions indicating other library errors + +@since version 3.0.0 +*/ +class out_of_range : public exception +{ + public: + static out_of_range create(int id_, const std::string& what_arg) + { + std::string w = exception::name("out_of_range", id_) + what_arg; + return out_of_range(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/*! +@brief exception indicating other library errors + +This exception is thrown in case of errors that cannot be classified with the +other exception types. + +Exceptions have ids 5xx. + +name / id | example message | description +------------------------------ | --------------- | ------------------------- +json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. + +@sa - @ref exception for the base class of the library exceptions +@sa - @ref parse_error for exceptions indicating a parse error +@sa - @ref invalid_iterator for exceptions indicating errors with iterators +@sa - @ref type_error for exceptions indicating executing a member function with + a wrong type +@sa - @ref out_of_range for exceptions indicating access out of the defined range + +@liveexample{The following code shows how an `other_error` exception can be +caught.,other_error} + +@since version 3.0.0 +*/ +class other_error : public exception +{ + public: + static other_error create(int id_, const std::string& what_arg) + { + std::string w = exception::name("other_error", id_) + what_arg; + return other_error(id_, w.c_str()); + } + + private: + JSON_HEDLEY_NON_NULL(3) + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type + +namespace nlohmann +{ +namespace detail +{ +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +template +using uncvref_t = typename std::remove_cv::type>::type; + +// implementation of C++14 index_sequence and affiliates +// source: https://stackoverflow.com/a/32223343 +template +struct index_sequence +{ + using type = index_sequence; + using value_type = std::size_t; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +template +struct merge_and_renumber; + +template +struct merge_and_renumber, index_sequence> + : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; + +template +struct make_index_sequence + : merge_and_renumber < typename make_index_sequence < N / 2 >::type, + typename make_index_sequence < N - N / 2 >::type > {}; + +template<> struct make_index_sequence<0> : index_sequence<> {}; +template<> struct make_index_sequence<1> : index_sequence<0> {}; + +template +using index_sequence_for = make_index_sequence; + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval + +// #include + + +#include // random_access_iterator_tag + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include + +// #include + + +// https://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; +} // namespace detail +} // namespace nlohmann + +// #include +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/*! +@brief JSON Pointer + +A JSON pointer defines a string syntax for identifying a specific value +within a JSON document. It can be used with functions `at` and +`operator[]`. Furthermore, JSON pointers are the base for JSON patches. + +@sa [RFC 6901](https://tools.ietf.org/html/rfc6901) + +@since version 2.0.0 +*/ +template +class json_pointer; + +/*! +@brief default JSON class + +This type is the default specialization of the @ref basic_json class which +uses the standard template types. + +@since version 1.0.0 +*/ +using json = basic_json<>; + +template +struct ordered_map; + +/*! +@brief ordered JSON class + +This type preserves the insertion order of object keys. + +@since version 3.9.0 +*/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +namespace nlohmann +{ +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using iterator_t = typename T::iterator; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, + enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + + +/////////////////// +// is_ functions // +/////////////////// + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +// source: https://stackoverflow.com/a/37193089/4116453 + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + std::is_constructible::value && + std::is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (std::is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (std::is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type_impl : std::false_type {}; + +template +struct is_compatible_string_type_impl < + BasicJsonType, CompatibleStringType, + enable_if_t::value >> +{ + static constexpr auto value = + std::is_constructible::value; +}; + +template +struct is_compatible_string_type + : is_compatible_string_type_impl {}; + +template +struct is_constructible_string_type_impl : std::false_type {}; + +template +struct is_constructible_string_type_impl < + BasicJsonType, ConstructibleStringType, + enable_if_t::value >> +{ + static constexpr auto value = + std::is_constructible::value; +}; + +template +struct is_constructible_string_type + : is_constructible_string_type_impl {}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < is_detected::value&& + is_detected::value&& +// This is needed because json_reverse_iterator has a ::iterator type... +// Therefore it is detected as a CompatibleArrayType. +// The real fix would be to have an Iterable concept. + !is_iterator_traits < + iterator_traits>::value >> +{ + static constexpr bool value = + std::is_constructible::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + std::is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_detected::value&& +is_complete_type < +detected_t>::value >> +{ + static constexpr bool value = + // This is needed because json_reverse_iterator has a ::iterator type, + // furthermore, std::back_insert_iterator (and other iterators) have a + // base class `iterator`... Therefore it is detected as a + // ConstructibleArrayType. The real fix would be to have an Iterable + // concept. + !is_iterator_traits>::value && + + (std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, typename ConstructibleArrayType::value_type >::value); +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + std::is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B1 { }; +template +struct conjunction +: std::conditional, B1>::type {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +namespace nlohmann +{ +namespace detail +{ +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +} +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +template +void from_json(const BasicJsonType& j, typename std::nullptr_t& n) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_null())) + { + JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()))); + } + n = nullptr; +} + +// overloads for basic_json template parameters +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < std::is_arithmetic::value&& + !std::is_same::value, + int > = 0 > +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); + } +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) + { + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); + } + b = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); + } + s = *j.template get_ptr(); +} + +template < + typename BasicJsonType, typename ConstructibleStringType, + enable_if_t < + is_constructible_string_type::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ConstructibleStringType& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); + } + + s = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, EnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +// forward_list doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::forward_list& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); + } + l.clear(); + std::transform(j.rbegin(), j.rend(), + std::front_inserter(l), [](const BasicJsonType & i) + { + return i.template get(); + }); +} + +// valarray doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::valarray& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); + } + l.resize(j.size()); + std::transform(j.begin(), j.end(), std::begin(l), + [](const BasicJsonType & elem) + { + return elem.template get(); + }); +} + +template +auto from_json(const BasicJsonType& j, T (&arr)[N]) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template +void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) +{ + arr = *j.template get_ptr(); +} + +template +auto from_json_array_impl(const BasicJsonType& j, std::array& arr, + priority_tag<2> /*unused*/) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template +auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) +-> decltype( + arr.reserve(std::declval()), + j.template get(), + void()) +{ + using std::end; + + ConstructibleArrayType ret; + ret.reserve(j.size()); + std::transform(j.begin(), j.end(), + std::inserter(ret, end(ret)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template +void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, + priority_tag<0> /*unused*/) +{ + using std::end; + + ConstructibleArrayType ret; + std::transform( + j.begin(), j.end(), std::inserter(ret, end(ret)), + [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template < typename BasicJsonType, typename ConstructibleArrayType, + enable_if_t < + is_constructible_array_type::value&& + !is_constructible_object_type::value&& + !is_constructible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) +-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), +j.template get(), +void()) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + + std::string(j.type_name()))); + } + + from_json_array_impl(j, arr, priority_tag<3> {}); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()))); + } + + bin = *j.template get_ptr(); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); + } + + ConstructibleObjectType ret; + auto inner_object = j.template get_ptr(); + using value_type = typename ConstructibleObjectType::value_type; + std::transform( + inner_object->begin(), inner_object->end(), + std::inserter(ret, ret.begin()), + [](typename BasicJsonType::object_t::value_type const & p) + { + return value_type(p.first, p.second.template get()); + }); + obj = std::move(ret); +} + +// overload for arithmetic types, not chosen for basic_json template arguments +// (BooleanType, etc..); note: Is it really necessary to provide explicit +// overloads for boolean_t etc. in case of a custom BooleanType which is not +// an arithmetic type? +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < + std::is_arithmetic::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); + } +} + +template +void from_json(const BasicJsonType& j, std::pair& p) +{ + p = {j.at(0).template get(), j.at(1).template get()}; +} + +template +void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence /*unused*/) +{ + t = std::make_tuple(j.at(Idx).template get::type>()...); +} + +template +void from_json(const BasicJsonType& j, std::tuple& t) +{ + from_json_tuple_impl(j, t, index_sequence_for {}); +} + +template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::unordered_map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +struct from_json_fn +{ + template + auto operator()(const BasicJsonType& j, T& val) const + noexcept(noexcept(from_json(j, val))) + -> decltype(from_json(j, val), void()) + { + return from_json(j, val); + } +}; +} // namespace detail + +/// namespace to hold default `from_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace +{ +constexpr const auto& from_json = detail::static_const::value; +} // namespace +} // namespace nlohmann + +// #include + + +#include // copy +#include // begin, end +#include // string +#include // tuple, get +#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type +#include // move, forward, declval, pair +#include // valarray +#include // vector + +// #include + + +#include // size_t +#include // input_iterator_tag +#include // string, to_string +#include // tuple_size, get, tuple_element + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +void int_to_string( string_type& target, std::size_t value ) +{ + // For ADL + using std::to_string; + target = to_string(value); +} +template class iteration_proxy_value +{ + public: + using difference_type = std::ptrdiff_t; + using value_type = iteration_proxy_value; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::input_iterator_tag; + using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; + + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + std::size_t array_index = 0; + /// last stringified array index + mutable std::size_t array_index_last = 0; + /// a string representation of the array index + mutable string_type array_index_str = "0"; + /// an empty string (to return a reference for primitive values) + const string_type empty_str = ""; + + public: + explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {} + + /// dereference operator (needed for range-based for) + iteration_proxy_value& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_value& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// equality operator (needed for InputIterator) + bool operator==(const iteration_proxy_value& o) const + { + return anchor == o.anchor; + } + + /// inequality operator (needed for range-based for) + bool operator!=(const iteration_proxy_value& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + const string_type& key() const + { + JSON_ASSERT(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + if (array_index != array_index_last) + { + int_to_string( array_index_str, array_index ); + array_index_last = array_index; + } + return array_index_str; + } + + // use key from the object + case value_t::object: + return anchor.key(); + + // use an empty key for all primitive types + default: + return empty_str; + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } +}; + +/// proxy class for the items() function +template class iteration_proxy +{ + private: + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) noexcept + : container(cont) {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_value begin() noexcept + { + return iteration_proxy_value(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_value end() noexcept + { + return iteration_proxy_value(container.end()); + } +}; +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) +{ + return i.key(); +} +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) +{ + return i.value(); +} +} // namespace detail +} // namespace nlohmann + +// The Addition to the STD Namespace is required to add +// Structured Bindings Support to the iteration_proxy_value class +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +namespace std +{ +#if defined(__clang__) + // Fix: https://github.com/nlohmann/json/issues/1401 + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wmismatched-tags" +#endif +template +class tuple_size<::nlohmann::detail::iteration_proxy_value> + : public std::integral_constant {}; + +template +class tuple_element> +{ + public: + using type = decltype( + get(std::declval < + ::nlohmann::detail::iteration_proxy_value> ())); +}; +#if defined(__clang__) + #pragma clang diagnostic pop +#endif +} // namespace std + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +////////////////// +// constructors // +////////////////// + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept + { + j.m_type = value_t::boolean; + j.m_value = b; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) + { + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) + { + j.m_type = value_t::string; + j.m_value = std::move(s); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleStringType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleStringType& str) + { + j.m_type = value_t::string; + j.m_value.string = j.template create(str); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) + { + j.m_type = value_t::binary; + typename BasicJsonType::binary_t value{b}; + j.m_value = value; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) + { + j.m_type = value_t::binary; + typename BasicJsonType::binary_t value{std::move(b)}; + j.m_value = value; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept + { + j.m_type = value_t::number_float; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept + { + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept + { + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) + { + j.m_type = value_t::array; + j.m_value = arr; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) + { + j.m_type = value_t::array; + j.m_value = std::move(arr); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleArrayType& arr) + { + using std::begin; + using std::end; + j.m_type = value_t::array; + j.m_value.array = j.template create(begin(arr), end(arr)); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, const std::vector& arr) + { + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->reserve(arr.size()); + for (const bool x : arr) + { + j.m_value.array->push_back(x); + } + j.assert_invariant(); + } + + template::value, int> = 0> + static void construct(BasicJsonType& j, const std::valarray& arr) + { + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->resize(arr.size()); + if (arr.size() > 0) + { + std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); + } + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) + { + j.m_type = value_t::object; + j.m_value = obj; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) + { + j.m_type = value_t::object; + j.m_value = std::move(obj); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < !std::is_same::value, int > = 0 > + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + using std::begin; + using std::end; + + j.m_type = value_t::object; + j.m_value.object = j.template create(begin(obj), end(obj)); + j.assert_invariant(); + } +}; + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +void to_json(BasicJsonType& j, T b) noexcept +{ + external_constructor::construct(j, b); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) +{ + external_constructor::construct(j, std::move(s)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, EnumType e) noexcept +{ + using underlying_type = typename std::underlying_type::type; + external_constructor::construct(j, static_cast(e)); +} + +template +void to_json(BasicJsonType& j, const std::vector& e) +{ + external_constructor::construct(j, e); +} + +template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < is_compatible_array_type::value&& + !is_compatible_object_type::value&& + !is_compatible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template +void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) +{ + external_constructor::construct(j, bin); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const std::valarray& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > +void to_json(BasicJsonType& j, const CompatibleObjectType& obj) +{ + external_constructor::construct(j, obj); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) +{ + external_constructor::construct(j, std::move(obj)); +} + +template < + typename BasicJsonType, typename T, std::size_t N, + enable_if_t < !std::is_constructible::value, + int > = 0 > +void to_json(BasicJsonType& j, const T(&arr)[N]) +{ + external_constructor::construct(j, arr); +} + +template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > +void to_json(BasicJsonType& j, const std::pair& p) +{ + j = { p.first, p.second }; +} + +// for https://github.com/nlohmann/json/pull/1134 +template>::value, int> = 0> +void to_json(BasicJsonType& j, const T& b) +{ + j = { {b.key(), b.value()} }; +} + +template +void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) +{ + j = { std::get(t)... }; +} + +template::value, int > = 0> +void to_json(BasicJsonType& j, const T& t) +{ + to_json_tuple_impl(j, t, make_index_sequence::value> {}); +} + +struct to_json_fn +{ + template + auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `to_json` function +namespace +{ +constexpr const auto& to_json = detail::static_const::value; +} // namespace +} // namespace nlohmann + + +namespace nlohmann +{ + +template +struct adl_serializer +{ + /*! + @brief convert a JSON value to any value type + + This function is usually called by the `get()` function of the + @ref basic_json class (either explicit or via conversion operators). + + @param[in] j JSON value to read from + @param[in,out] val value to write to + */ + template + static auto from_json(BasicJsonType&& j, ValueType& val) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), val))) + -> decltype(::nlohmann::from_json(std::forward(j), val), void()) + { + ::nlohmann::from_json(std::forward(j), val); + } + + /*! + @brief convert any value type to a JSON value + + This function is usually called by the constructors of the @ref basic_json + class. + + @param[in,out] j JSON value to write to + @param[in] val value to read from + */ + template + static auto to_json(BasicJsonType& j, ValueType&& val) noexcept( + noexcept(::nlohmann::to_json(j, std::forward(val)))) + -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) + { + ::nlohmann::to_json(j, std::forward(val)); + } +}; + +} // namespace nlohmann + +// #include + + +#include // uint8_t +#include // tie +#include // move + +namespace nlohmann +{ + +/*! +@brief an internal type for a backed binary type + +This type extends the template parameter @a BinaryType provided to `basic_json` +with a subtype used by BSON and MessagePack. This type exists so that the user +does not have to specify a type themselves with a specific naming scheme in +order to override the binary type. + +@tparam BinaryType container to store bytes (`std::vector` by + default) + +@since version 3.8.0 +*/ +template +class byte_container_with_subtype : public BinaryType +{ + public: + /// the type of the underlying container + using container_type = BinaryType; + + byte_container_with_subtype() noexcept(noexcept(container_type())) + : container_type() + {} + + byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) + : container_type(b) + {} + + byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + {} + + byte_container_with_subtype(const container_type& b, std::uint8_t subtype) noexcept(noexcept(container_type(b))) + : container_type(b) + , m_subtype(subtype) + , m_has_subtype(true) + {} + + byte_container_with_subtype(container_type&& b, std::uint8_t subtype) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + , m_subtype(subtype) + , m_has_subtype(true) + {} + + bool operator==(const byte_container_with_subtype& rhs) const + { + return std::tie(static_cast(*this), m_subtype, m_has_subtype) == + std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); + } + + bool operator!=(const byte_container_with_subtype& rhs) const + { + return !(rhs == *this); + } + + /*! + @brief sets the binary subtype + + Sets the binary subtype of the value, also flags a binary JSON value as + having a subtype, which has implications for serialization. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa @ref subtype() -- return the binary subtype + @sa @ref clear_subtype() -- clears the binary subtype + @sa @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + void set_subtype(std::uint8_t subtype) noexcept + { + m_subtype = subtype; + m_has_subtype = true; + } + + /*! + @brief return the binary subtype + + Returns the numerical subtype of the value if it has a subtype. If it does + not have a subtype, this function will return size_t(-1) as a sentinel + value. + + @return the numerical subtype of the binary value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa @ref set_subtype() -- sets the binary subtype + @sa @ref clear_subtype() -- clears the binary subtype + @sa @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + constexpr std::uint8_t subtype() const noexcept + { + return m_subtype; + } + + /*! + @brief return whether the value has a subtype + + @return whether the value has a subtype + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa @ref subtype() -- return the binary subtype + @sa @ref set_subtype() -- sets the binary subtype + @sa @ref clear_subtype() -- clears the binary subtype + + @since version 3.8.0 + */ + constexpr bool has_subtype() const noexcept + { + return m_has_subtype; + } + + /*! + @brief clears the binary subtype + + Clears the binary subtype and flags the value as not having a subtype, which + has implications for serialization; for instance MessagePack will prefer the + bin family over the ext family. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @sa @ref subtype() -- return the binary subtype + @sa @ref set_subtype() -- sets the binary subtype + @sa @ref has_subtype() -- returns whether or not the binary value has a + subtype + + @since version 3.8.0 + */ + void clear_subtype() noexcept + { + m_subtype = 0; + m_has_subtype = false; + } + + private: + std::uint8_t m_subtype = 0; + bool m_has_subtype = false; +}; + +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + + +#include // size_t, uint8_t +#include // hash + +namespace nlohmann +{ +namespace detail +{ + +// boost::hash_combine +inline std::size_t combine(std::size_t seed, std::size_t h) noexcept +{ + seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); + return seed; +} + +/*! +@brief hash a JSON value + +The hash function tries to rely on std::hash where possible. Furthermore, the +type of the JSON value is taken into account to have different hash values for +null, 0, 0U, and false, etc. + +@tparam BasicJsonType basic_json specialization +@param j JSON value to hash +@return hash value of j +*/ +template +std::size_t hash(const BasicJsonType& j) +{ + using string_t = typename BasicJsonType::string_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + + const auto type = static_cast(j.type()); + switch (j.type()) + { + case BasicJsonType::value_t::null: + case BasicJsonType::value_t::discarded: + { + return combine(type, 0); + } + + case BasicJsonType::value_t::object: + { + auto seed = combine(type, j.size()); + for (const auto& element : j.items()) + { + const auto h = std::hash {}(element.key()); + seed = combine(seed, h); + seed = combine(seed, hash(element.value())); + } + return seed; + } + + case BasicJsonType::value_t::array: + { + auto seed = combine(type, j.size()); + for (const auto& element : j) + { + seed = combine(seed, hash(element)); + } + return seed; + } + + case BasicJsonType::value_t::string: + { + const auto h = std::hash {}(j.template get_ref()); + return combine(type, h); + } + + case BasicJsonType::value_t::boolean: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_integer: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case nlohmann::detail::value_t::number_unsigned: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case nlohmann::detail::value_t::number_float: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case nlohmann::detail::value_t::binary: + { + auto seed = combine(type, j.get_binary().size()); + const auto h = std::hash {}(j.get_binary().has_subtype()); + seed = combine(seed, h); + seed = combine(seed, j.get_binary().subtype()); + for (const auto byte : j.get_binary()) + { + seed = combine(seed, std::hash {}(byte)); + } + return seed; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // generate_n +#include // array +#include // ldexp +#include // size_t +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // snprintf +#include // memcpy +#include // back_inserter +#include // numeric_limits +#include // char_traits, string +#include // make_pair, move + +// #include + +// #include + + +#include // array +#include // size_t +#include //FILE * +#include // strlen +#include // istream +#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next +#include // shared_ptr, make_shared, addressof +#include // accumulate +#include // string, char_traits +#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer +#include // pair, declval + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// the supported input formats +enum class input_format_t { json, cbor, msgpack, ubjson, bson }; + +//////////////////// +// input adapters // +//////////////////// + +/*! +Input adapter for stdio file access. This adapter read only 1 byte and do not use any + buffer. This adapter is a very low level adapter. +*/ +class file_input_adapter +{ + public: + using char_type = char; + + JSON_HEDLEY_NON_NULL(2) + explicit file_input_adapter(std::FILE* f) noexcept + : m_file(f) + {} + + // make class move-only + file_input_adapter(const file_input_adapter&) = delete; + file_input_adapter(file_input_adapter&&) = default; + file_input_adapter& operator=(const file_input_adapter&) = delete; + file_input_adapter& operator=(file_input_adapter&&) = delete; + + std::char_traits::int_type get_character() noexcept + { + return std::fgetc(m_file); + } + + private: + /// the file pointer to read from + std::FILE* m_file; +}; + + +/*! +Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at +beginning of input. Does not support changing the underlying std::streambuf +in mid-input. Maintains underlying std::istream and std::streambuf to support +subsequent use of standard std::istream operations to process any input +characters following those used in parsing the JSON input. Clears the +std::istream flags; any input errors (e.g., EOF) will be detected by the first +subsequent call for input from the std::istream. +*/ +class input_stream_adapter +{ + public: + using char_type = char; + + ~input_stream_adapter() + { + // clear stream flags; we use underlying streambuf I/O, do not + // maintain ifstream flags, except eof + if (is != nullptr) + { + is->clear(is->rdstate() & std::ios::eofbit); + } + } + + explicit input_stream_adapter(std::istream& i) + : is(&i), sb(i.rdbuf()) + {} + + // delete because of pointer members + input_stream_adapter(const input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&& rhs) = delete; + + input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) + { + rhs.is = nullptr; + rhs.sb = nullptr; + } + + // std::istream/std::streambuf use std::char_traits::to_int_type, to + // ensure that std::char_traits::eof() and the character 0xFF do not + // end up as the same value, eg. 0xFFFFFFFF. + std::char_traits::int_type get_character() + { + auto res = sb->sbumpc(); + // set eof manually, as we don't use the istream interface. + if (JSON_HEDLEY_UNLIKELY(res == EOF)) + { + is->clear(is->rdstate() | std::ios::eofbit); + } + return res; + } + + private: + /// the associated input stream + std::istream* is = nullptr; + std::streambuf* sb = nullptr; +}; + +// General-purpose iterator-based adapter. It might not be as fast as +// theoretically possible for some containers, but it is extremely versatile. +template +class iterator_input_adapter +{ + public: + using char_type = typename std::iterator_traits::value_type; + + iterator_input_adapter(IteratorType first, IteratorType last) + : current(std::move(first)), end(std::move(last)) {} + + typename std::char_traits::int_type get_character() + { + if (JSON_HEDLEY_LIKELY(current != end)) + { + auto result = std::char_traits::to_int_type(*current); + std::advance(current, 1); + return result; + } + else + { + return std::char_traits::eof(); + } + } + + private: + IteratorType current; + IteratorType end; + + template + friend struct wide_string_input_helper; + + bool empty() const + { + return current == end; + } + +}; + + +template +struct wide_string_input_helper; + +template +struct wide_string_input_helper +{ + // UTF-32 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-32 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (wc <= 0xFFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else if (wc <= 0x10FFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + // unknown character + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } +}; + +template +struct wide_string_input_helper +{ + // UTF-16 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-16 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (0xD800 > wc || wc >= 0xE000) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else + { + if (JSON_HEDLEY_UNLIKELY(!input.empty())) + { + const auto wc2 = static_cast(input.get_character()); + const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); + utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } + } +}; + +// Wraps another input apdater to convert wide character types into individual bytes. +template +class wide_string_input_adapter +{ + public: + using char_type = char; + + wide_string_input_adapter(BaseInputAdapter base) + : base_adapter(base) {} + + typename std::char_traits::int_type get_character() noexcept + { + // check if buffer needs to be filled + if (utf8_bytes_index == utf8_bytes_filled) + { + fill_buffer(); + + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index == 0); + } + + // use buffer + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); + return utf8_bytes[utf8_bytes_index++]; + } + + private: + BaseInputAdapter base_adapter; + + template + void fill_buffer() + { + wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); + } + + /// a buffer for UTF-8 bytes + std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; + + /// index to the utf8_codes array for the next valid byte + std::size_t utf8_bytes_index = 0; + /// number of valid bytes in the utf8_codes array + std::size_t utf8_bytes_filled = 0; +}; + + +template +struct iterator_input_adapter_factory +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using adapter_type = iterator_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(std::move(first), std::move(last)); + } +}; + +template +struct is_iterator_of_multibyte +{ + using value_type = typename std::iterator_traits::value_type; + enum + { + value = sizeof(value_type) > 1 + }; +}; + +template +struct iterator_input_adapter_factory::value>> +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using base_adapter_type = iterator_input_adapter; + using adapter_type = wide_string_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(base_adapter_type(std::move(first), std::move(last))); + } +}; + +// General purpose iterator-based input +template +typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) +{ + using factory_type = iterator_input_adapter_factory; + return factory_type::create(first, last); +} + +// Convenience shorthand from container to iterator +template +auto input_adapter(const ContainerType& container) -> decltype(input_adapter(begin(container), end(container))) +{ + // Enable ADL + using std::begin; + using std::end; + + return input_adapter(begin(container), end(container)); +} + +// Special cases with fast paths +inline file_input_adapter input_adapter(std::FILE* file) +{ + return file_input_adapter(file); +} + +inline input_stream_adapter input_adapter(std::istream& stream) +{ + return input_stream_adapter(stream); +} + +inline input_stream_adapter input_adapter(std::istream&& stream) +{ + return input_stream_adapter(stream); +} + +using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); + +// Null-delimited strings, and the like. +template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + !std::is_array::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > +contiguous_bytes_input_adapter input_adapter(CharT b) +{ + auto length = std::strlen(reinterpret_cast(b)); + const auto* ptr = reinterpret_cast(b); + return input_adapter(ptr, ptr + length); +} + +template +auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) +{ + return input_adapter(array, array + N); +} + +// This class only handles inputs of input_buffer_adapter type. +// It's required so that expressions like {ptr, len} can be implicitely casted +// to the correct adapter. +class span_input_adapter +{ + public: + template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > + span_input_adapter(CharT b, std::size_t l) + : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} + + template::iterator_category, std::random_access_iterator_tag>::value, + int>::type = 0> + span_input_adapter(IteratorType first, IteratorType last) + : ia(input_adapter(first, last)) {} + + contiguous_bytes_input_adapter&& get() + { + return std::move(ia); + } + + private: + contiguous_bytes_input_adapter ia; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +#include // string +#include // move +#include // vector + +// #include + +// #include + + +namespace nlohmann +{ + +/*! +@brief SAX interface + +This class describes the SAX interface used by @ref nlohmann::json::sax_parse. +Each function is called in different situations while the input is parsed. The +boolean return value informs the parser whether to continue processing the +input. +*/ +template +struct json_sax +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @brief a null value was read + @return whether parsing should proceed + */ + virtual bool null() = 0; + + /*! + @brief a boolean value was read + @param[in] val boolean value + @return whether parsing should proceed + */ + virtual bool boolean(bool val) = 0; + + /*! + @brief an integer number was read + @param[in] val integer value + @return whether parsing should proceed + */ + virtual bool number_integer(number_integer_t val) = 0; + + /*! + @brief an unsigned integer number was read + @param[in] val unsigned integer value + @return whether parsing should proceed + */ + virtual bool number_unsigned(number_unsigned_t val) = 0; + + /*! + @brief an floating-point number was read + @param[in] val floating-point value + @param[in] s raw token value + @return whether parsing should proceed + */ + virtual bool number_float(number_float_t val, const string_t& s) = 0; + + /*! + @brief a string was read + @param[in] val string value + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool string(string_t& val) = 0; + + /*! + @brief a binary string was read + @param[in] val binary value + @return whether parsing should proceed + @note It is safe to move the passed binary. + */ + virtual bool binary(binary_t& val) = 0; + + /*! + @brief the beginning of an object was read + @param[in] elements number of object elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_object(std::size_t elements) = 0; + + /*! + @brief an object key was read + @param[in] val object key + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool key(string_t& val) = 0; + + /*! + @brief the end of an object was read + @return whether parsing should proceed + */ + virtual bool end_object() = 0; + + /*! + @brief the beginning of an array was read + @param[in] elements number of array elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_array(std::size_t elements) = 0; + + /*! + @brief the end of an array was read + @return whether parsing should proceed + */ + virtual bool end_array() = 0; + + /*! + @brief a parse error occurred + @param[in] position the position in the input where the error occurs + @param[in] last_token the last read token + @param[in] ex an exception object describing the error + @return whether parsing should proceed (must return false) + */ + virtual bool parse_error(std::size_t position, + const std::string& last_token, + const detail::exception& ex) = 0; + + virtual ~json_sax() = default; +}; + + +namespace detail +{ +/*! +@brief SAX implementation to create a JSON value from SAX events + +This class implements the @ref json_sax interface and processes the SAX events +to create a JSON value which makes it basically a DOM parser. The structure or +hierarchy of the JSON value is managed by the stack `ref_stack` which contains +a pointer to the respective array or object for each recursion depth. + +After successful parsing, the value that is passed by reference to the +constructor contains the parsed value. + +@tparam BasicJsonType the JSON type +*/ +template +class json_sax_dom_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @param[in, out] r reference to a JSON value that is manipulated while + parsing + @param[in] allow_exceptions_ whether parse errors yield exceptions + */ + explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) + : root(r), allow_exceptions(allow_exceptions_) + {} + + // make class move-only + json_sax_dom_parser(const json_sax_dom_parser&) = delete; + json_sax_dom_parser(json_sax_dom_parser&&) = default; + json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; + json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; + ~json_sax_dom_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); + + if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, + "excessive object size: " + std::to_string(len))); + } + + return true; + } + + bool key(string_t& val) + { + // add null at given key and store the reference for later + object_element = &(ref_stack.back()->m_value.object->operator[](val)); + return true; + } + + bool end_object() + { + ref_stack.pop_back(); + return true; + } + + bool start_array(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); + + if (JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, + "excessive array size: " + std::to_string(len))); + } + + return true; + } + + bool end_array() + { + ref_stack.pop_back(); + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + */ + template + JSON_HEDLEY_RETURNS_NON_NULL + BasicJsonType* handle_value(Value&& v) + { + if (ref_stack.empty()) + { + root = BasicJsonType(std::forward(v)); + return &root; + } + + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::forward(v)); + return &(ref_stack.back()->m_value.array->back()); + } + + JSON_ASSERT(ref_stack.back()->is_object()); + JSON_ASSERT(object_element); + *object_element = BasicJsonType(std::forward(v)); + return object_element; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +template +class json_sax_dom_callback_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using parser_callback_t = typename BasicJsonType::parser_callback_t; + using parse_event_t = typename BasicJsonType::parse_event_t; + + json_sax_dom_callback_parser(BasicJsonType& r, + const parser_callback_t cb, + const bool allow_exceptions_ = true) + : root(r), callback(cb), allow_exceptions(allow_exceptions_) + { + keep_stack.push_back(true); + } + + // make class move-only + json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; + json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; + ~json_sax_dom_callback_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + // check callback for object start + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::object, true); + ref_stack.push_back(val.second); + + // check object limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len))); + } + + return true; + } + + bool key(string_t& val) + { + BasicJsonType k = BasicJsonType(val); + + // check callback for key + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); + key_keep_stack.push_back(keep); + + // add discarded value at given key and store the reference for later + if (keep && ref_stack.back()) + { + object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); + } + + return true; + } + + bool end_object() + { + if (ref_stack.back() && !callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) + { + // discard object + *ref_stack.back() = discarded; + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) + { + // remove discarded value + for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) + { + if (it->is_discarded()) + { + ref_stack.back()->erase(it); + break; + } + } + } + + return true; + } + + bool start_array(std::size_t len) + { + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::array, true); + ref_stack.push_back(val.second); + + // check array limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != std::size_t(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len))); + } + + return true; + } + + bool end_array() + { + bool keep = true; + + if (ref_stack.back()) + { + keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); + if (!keep) + { + // discard array + *ref_stack.back() = discarded; + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + // remove discarded value + if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->pop_back(); + } + + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @param[in] v value to add to the JSON value we build during parsing + @param[in] skip_callback whether we should skip calling the callback + function; this is required after start_array() and + start_object() SAX events, because otherwise we would call the + callback function with an empty array or object, respectively. + + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + + @return pair of boolean (whether value should be kept) and pointer (to the + passed value in the ref_stack hierarchy; nullptr if not kept) + */ + template + std::pair handle_value(Value&& v, const bool skip_callback = false) + { + JSON_ASSERT(!keep_stack.empty()); + + // do not handle this value if we know it would be added to a discarded + // container + if (!keep_stack.back()) + { + return {false, nullptr}; + } + + // create value + auto value = BasicJsonType(std::forward(v)); + + // check callback + const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); + + // do not handle this value if we just learnt it shall be discarded + if (!keep) + { + return {false, nullptr}; + } + + if (ref_stack.empty()) + { + root = std::move(value); + return {true, &root}; + } + + // skip this value if we already decided to skip the parent + // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) + if (!ref_stack.back()) + { + return {false, nullptr}; + } + + // we now only expect arrays and objects + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + // array + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->push_back(std::move(value)); + return {true, &(ref_stack.back()->m_value.array->back())}; + } + + // object + JSON_ASSERT(ref_stack.back()->is_object()); + // check if we should store an element for the current key + JSON_ASSERT(!key_keep_stack.empty()); + const bool store_element = key_keep_stack.back(); + key_keep_stack.pop_back(); + + if (!store_element) + { + return {false, nullptr}; + } + + JSON_ASSERT(object_element); + *object_element = std::move(value); + return {true, object_element}; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// stack to manage which values to keep + std::vector keep_stack {}; + /// stack to manage which object keys to keep + std::vector key_keep_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// callback function + const parser_callback_t callback = nullptr; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; + /// a discarded value for the callback + BasicJsonType discarded = BasicJsonType::value_t::discarded; +}; + +template +class json_sax_acceptor +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + bool null() + { + return true; + } + + bool boolean(bool /*unused*/) + { + return true; + } + + bool number_integer(number_integer_t /*unused*/) + { + return true; + } + + bool number_unsigned(number_unsigned_t /*unused*/) + { + return true; + } + + bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) + { + return true; + } + + bool string(string_t& /*unused*/) + { + return true; + } + + bool binary(binary_t& /*unused*/) + { + return true; + } + + bool start_object(std::size_t /*unused*/ = std::size_t(-1)) + { + return true; + } + + bool key(string_t& /*unused*/) + { + return true; + } + + bool end_object() + { + return true; + } + + bool start_array(std::size_t /*unused*/ = std::size_t(-1)) + { + return true; + } + + bool end_array() + { + return true; + } + + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) + { + return false; + } +}; +} // namespace detail + +} // namespace nlohmann + +// #include + + +#include // array +#include // localeconv +#include // size_t +#include // snprintf +#include // strtof, strtod, strtold, strtoll, strtoull +#include // initializer_list +#include // char_traits, string +#include // move +#include // vector + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////// +// lexer // +/////////// + +template +class lexer_base +{ + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value + value_integer, ///< a signed integer -- use get_number_integer() for actual value + value_float, ///< an floating point number -- use get_number_float() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input, ///< indicating the end of the input buffer + literal_or_value ///< a literal or the begin of a value (only for diagnostics) + }; + + /// return name of values of type token_type (only used for errors) + JSON_HEDLEY_RETURNS_NON_NULL + JSON_HEDLEY_CONST + static const char* token_type_name(const token_type t) noexcept + { + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case token_type::value_unsigned: + case token_type::value_integer: + case token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + case token_type::literal_or_value: + return "'[', '{', or a literal"; + // LCOV_EXCL_START + default: // catch non-enum values + return "unknown token"; + // LCOV_EXCL_STOP + } + } +}; +/*! +@brief lexical analysis + +This class organizes the lexical analysis during JSON deserialization. +*/ +template +class lexer : public lexer_base +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + using token_type = typename lexer_base::token_type; + + explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) + : ia(std::move(adapter)) + , ignore_comments(ignore_comments_) + , decimal_point_char(static_cast(get_decimal_point())) + {} + + // delete because of pointer members + lexer(const lexer&) = delete; + lexer(lexer&&) = default; + lexer& operator=(lexer&) = delete; + lexer& operator=(lexer&&) = default; + ~lexer() = default; + + private: + ///////////////////// + // locales + ///////////////////// + + /// return the locale-dependent decimal point + JSON_HEDLEY_PURE + static char get_decimal_point() noexcept + { + const auto* loc = localeconv(); + JSON_ASSERT(loc != nullptr); + return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); + } + + ///////////////////// + // scan functions + ///////////////////// + + /*! + @brief get codepoint from 4 hex characters following `\u` + + For input "\u c1 c2 c3 c4" the codepoint is: + (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 + = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) + + Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' + must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The + conversion is done by subtracting the offset (0x30, 0x37, and 0x57) + between the ASCII value of the character and the desired integer value. + + @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or + non-hex character) + */ + int get_codepoint() + { + // this function only makes sense after reading `\u` + JSON_ASSERT(current == 'u'); + int codepoint = 0; + + const auto factors = { 12u, 8u, 4u, 0u }; + for (const auto factor : factors) + { + get(); + + if (current >= '0' && current <= '9') + { + codepoint += static_cast((static_cast(current) - 0x30u) << factor); + } + else if (current >= 'A' && current <= 'F') + { + codepoint += static_cast((static_cast(current) - 0x37u) << factor); + } + else if (current >= 'a' && current <= 'f') + { + codepoint += static_cast((static_cast(current) - 0x57u) << factor); + } + else + { + return -1; + } + } + + JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); + return codepoint; + } + + /*! + @brief check if the next byte(s) are inside a given range + + Adds the current byte and, for each passed range, reads a new byte and + checks if it is inside the range. If a violation was detected, set up an + error message and return false. Otherwise, return true. + + @param[in] ranges list of integers; interpreted as list of pairs of + inclusive lower and upper bound, respectively + + @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, + 1, 2, or 3 pairs. This precondition is enforced by an assertion. + + @return true if and only if no range violation was detected + */ + bool next_byte_in_range(std::initializer_list ranges) + { + JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); + add(current); + + for (auto range = ranges.begin(); range != ranges.end(); ++range) + { + get(); + if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) + { + add(current); + } + else + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return false; + } + } + + return true; + } + + /*! + @brief scan a string literal + + This function scans a string according to Sect. 7 of RFC 7159. While + scanning, bytes are escaped and copied into buffer token_buffer. Then the + function returns successfully, token_buffer is *not* null-terminated (as it + may contain \0 bytes), and token_buffer.size() is the number of bytes in the + string. + + @return token_type::value_string if string could be successfully scanned, + token_type::parse_error otherwise + + @note In case of errors, variable error_message contains a textual + description. + */ + token_type scan_string() + { + // reset token_buffer (ignore opening quote) + reset(); + + // we entered the function by reading an open quote + JSON_ASSERT(current == '\"'); + + while (true) + { + // get next character + switch (get()) + { + // end of file while parsing string + case std::char_traits::eof(): + { + error_message = "invalid string: missing closing quote"; + return token_type::parse_error; + } + + // closing quote + case '\"': + { + return token_type::value_string; + } + + // escapes + case '\\': + { + switch (get()) + { + // quotation mark + case '\"': + add('\"'); + break; + // reverse solidus + case '\\': + add('\\'); + break; + // solidus + case '/': + add('/'); + break; + // backspace + case 'b': + add('\b'); + break; + // form feed + case 'f': + add('\f'); + break; + // line feed + case 'n': + add('\n'); + break; + // carriage return + case 'r': + add('\r'); + break; + // tab + case 't': + add('\t'); + break; + + // unicode escapes + case 'u': + { + const int codepoint1 = get_codepoint(); + int codepoint = codepoint1; // start with codepoint1 + + if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if code point is a high surrogate + if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) + { + // expect next \uxxxx entry + if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) + { + const int codepoint2 = get_codepoint(); + + if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if codepoint2 is a low surrogate + if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) + { + // overwrite codepoint + codepoint = static_cast( + // high surrogate occupies the most significant 22 bits + (static_cast(codepoint1) << 10u) + // low surrogate occupies the least significant 15 bits + + static_cast(codepoint2) + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00u); + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) + { + error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; + return token_type::parse_error; + } + } + + // result of the above calculation yields a proper codepoint + JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); + + // translate codepoint into bytes + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + add(static_cast(codepoint)); + } + else if (codepoint <= 0x7FF) + { + // 2-byte characters: 110xxxxx 10xxxxxx + add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else if (codepoint <= 0xFFFF) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + + break; + } + + // other characters after escape + default: + error_message = "invalid string: forbidden character after backslash"; + return token_type::parse_error; + } + + break; + } + + // invalid control characters + case 0x00: + { + error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; + return token_type::parse_error; + } + + case 0x01: + { + error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; + return token_type::parse_error; + } + + case 0x02: + { + error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; + return token_type::parse_error; + } + + case 0x03: + { + error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; + return token_type::parse_error; + } + + case 0x04: + { + error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; + return token_type::parse_error; + } + + case 0x05: + { + error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; + return token_type::parse_error; + } + + case 0x06: + { + error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; + return token_type::parse_error; + } + + case 0x07: + { + error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; + return token_type::parse_error; + } + + case 0x08: + { + error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; + return token_type::parse_error; + } + + case 0x09: + { + error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; + return token_type::parse_error; + } + + case 0x0A: + { + error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; + return token_type::parse_error; + } + + case 0x0B: + { + error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; + return token_type::parse_error; + } + + case 0x0C: + { + error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; + return token_type::parse_error; + } + + case 0x0D: + { + error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; + return token_type::parse_error; + } + + case 0x0E: + { + error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; + return token_type::parse_error; + } + + case 0x0F: + { + error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; + return token_type::parse_error; + } + + case 0x10: + { + error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; + return token_type::parse_error; + } + + case 0x11: + { + error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; + return token_type::parse_error; + } + + case 0x12: + { + error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; + return token_type::parse_error; + } + + case 0x13: + { + error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; + return token_type::parse_error; + } + + case 0x14: + { + error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; + return token_type::parse_error; + } + + case 0x15: + { + error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; + return token_type::parse_error; + } + + case 0x16: + { + error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; + return token_type::parse_error; + } + + case 0x17: + { + error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; + return token_type::parse_error; + } + + case 0x18: + { + error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; + return token_type::parse_error; + } + + case 0x19: + { + error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; + return token_type::parse_error; + } + + case 0x1A: + { + error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; + return token_type::parse_error; + } + + case 0x1B: + { + error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; + return token_type::parse_error; + } + + case 0x1C: + { + error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; + return token_type::parse_error; + } + + case 0x1D: + { + error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; + return token_type::parse_error; + } + + case 0x1E: + { + error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; + return token_type::parse_error; + } + + case 0x1F: + { + error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; + return token_type::parse_error; + } + + // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) + case 0x20: + case 0x21: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + { + add(current); + break; + } + + // U+0080..U+07FF: bytes C2..DF 80..BF + case 0xC2: + case 0xC3: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD5: + case 0xD6: + case 0xD7: + case 0xD8: + case 0xD9: + case 0xDA: + case 0xDB: + case 0xDC: + case 0xDD: + case 0xDE: + case 0xDF: + { + if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) + { + return token_type::parse_error; + } + break; + } + + // U+0800..U+0FFF: bytes E0 A0..BF 80..BF + case 0xE0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF + // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xEE: + case 0xEF: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+D000..U+D7FF: bytes ED 80..9F 80..BF + case 0xED: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF + case 0xF0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF + case 0xF1: + case 0xF2: + case 0xF3: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF + case 0xF4: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // remaining bytes (80..C1 and F5..FF) are ill-formed + default: + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + } + } + } + + /*! + * @brief scan a comment + * @return whether comment could be scanned successfully + */ + bool scan_comment() + { + switch (get()) + { + // single-line comments skip input until a newline or EOF is read + case '/': + { + while (true) + { + switch (get()) + { + case '\n': + case '\r': + case std::char_traits::eof(): + case '\0': + return true; + + default: + break; + } + } + } + + // multi-line comments skip input until */ is read + case '*': + { + while (true) + { + switch (get()) + { + case std::char_traits::eof(): + case '\0': + { + error_message = "invalid comment; missing closing '*/'"; + return false; + } + + case '*': + { + switch (get()) + { + case '/': + return true; + + default: + { + unget(); + continue; + } + } + } + + default: + continue; + } + } + } + + // unexpected character after reading '/' + default: + { + error_message = "invalid comment; expecting '/' or '*' after '/'"; + return false; + } + } + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(float& f, const char* str, char** endptr) noexcept + { + f = std::strtof(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(double& f, const char* str, char** endptr) noexcept + { + f = std::strtod(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(long double& f, const char* str, char** endptr) noexcept + { + f = std::strtold(str, endptr); + } + + /*! + @brief scan a number literal + + This function scans a string according to Sect. 6 of RFC 7159. + + The function is realized with a deterministic finite state machine derived + from the grammar described in RFC 7159. Starting in state "init", the + input is read and used to determined the next state. Only state "done" + accepts the number. State "error" is a trap state to model errors. In the + table below, "anything" means any character but the ones listed before. + + state | 0 | 1-9 | e E | + | - | . | anything + ---------|----------|----------|----------|---------|---------|----------|----------- + init | zero | any1 | [error] | [error] | minus | [error] | [error] + minus | zero | any1 | [error] | [error] | [error] | [error] | [error] + zero | done | done | exponent | done | done | decimal1 | done + any1 | any1 | any1 | exponent | done | done | decimal1 | done + decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] + decimal2 | decimal2 | decimal2 | exponent | done | done | done | done + exponent | any2 | any2 | [error] | sign | sign | [error] | [error] + sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] + any2 | any2 | any2 | done | done | done | done | done + + The state machine is realized with one label per state (prefixed with + "scan_number_") and `goto` statements between them. The state machine + contains cycles, but any cycle can be left when EOF is read. Therefore, + the function is guaranteed to terminate. + + During scanning, the read bytes are stored in token_buffer. This string is + then converted to a signed integer, an unsigned integer, or a + floating-point number. + + @return token_type::value_unsigned, token_type::value_integer, or + token_type::value_float if number could be successfully scanned, + token_type::parse_error otherwise + + @note The scanner is independent of the current locale. Internally, the + locale's decimal point is used instead of `.` to work with the + locale-dependent converters. + */ + token_type scan_number() // lgtm [cpp/use-of-goto] + { + // reset token_buffer to store the number's bytes + reset(); + + // the type of the parsed number; initially set to unsigned; will be + // changed if minus sign, decimal point or exponent is read + token_type number_type = token_type::value_unsigned; + + // state (init): we just found out we need to scan a number + switch (current) + { + case '-': + { + add(current); + goto scan_number_minus; + } + + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + // all other characters are rejected outside scan_number() + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + +scan_number_minus: + // state: we just parsed a leading minus sign + number_type = token_type::value_integer; + switch (get()) + { + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + error_message = "invalid number; expected digit after '-'"; + return token_type::parse_error; + } + } + +scan_number_zero: + // state: we just parse a zero (maybe with a leading minus sign) + switch (get()) + { + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_any1: + // state: we just parsed a number 0-9 (maybe with a leading minus sign) + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_decimal1: + // state: we just parsed a decimal point + number_type = token_type::value_float; + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + default: + { + error_message = "invalid number; expected digit after '.'"; + return token_type::parse_error; + } + } + +scan_number_decimal2: + // we just parsed at least one number after a decimal point + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_exponent: + // we just parsed an exponent + number_type = token_type::value_float; + switch (get()) + { + case '+': + case '-': + { + add(current); + goto scan_number_sign; + } + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = + "invalid number; expected '+', '-', or digit after exponent"; + return token_type::parse_error; + } + } + +scan_number_sign: + // we just parsed an exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected digit after exponent sign"; + return token_type::parse_error; + } + } + +scan_number_any2: + // we just parsed a number after the exponent or exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + goto scan_number_done; + } + +scan_number_done: + // unget the character after the number (we only read it to know that + // we are done scanning a number) + unget(); + + char* endptr = nullptr; + errno = 0; + + // try to parse integers first and fall back to floats + if (number_type == token_type::value_unsigned) + { + const auto x = std::strtoull(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_unsigned = static_cast(x); + if (value_unsigned == x) + { + return token_type::value_unsigned; + } + } + } + else if (number_type == token_type::value_integer) + { + const auto x = std::strtoll(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_integer = static_cast(x); + if (value_integer == x) + { + return token_type::value_integer; + } + } + } + + // this code is reached if we parse a floating-point number or if an + // integer conversion above failed + strtof(value_float, token_buffer.data(), &endptr); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + return token_type::value_float; + } + + /*! + @param[in] literal_text the literal text to expect + @param[in] length the length of the passed literal text + @param[in] return_type the token type to return on success + */ + JSON_HEDLEY_NON_NULL(2) + token_type scan_literal(const char_type* literal_text, const std::size_t length, + token_type return_type) + { + JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); + for (std::size_t i = 1; i < length; ++i) + { + if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) + { + error_message = "invalid literal"; + return token_type::parse_error; + } + } + return return_type; + } + + ///////////////////// + // input management + ///////////////////// + + /// reset token_buffer; current character is beginning of token + void reset() noexcept + { + token_buffer.clear(); + token_string.clear(); + token_string.push_back(std::char_traits::to_char_type(current)); + } + + /* + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a + `std::char_traits::eof()` in that case. Stores the scanned characters + for use in error messages. + + @return character read from the input + */ + char_int_type get() + { + ++position.chars_read_total; + ++position.chars_read_current_line; + + if (next_unget) + { + // just reset the next_unget variable and work with current + next_unget = false; + } + else + { + current = ia.get_character(); + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + token_string.push_back(std::char_traits::to_char_type(current)); + } + + if (current == '\n') + { + ++position.lines_read; + position.chars_read_current_line = 0; + } + + return current; + } + + /*! + @brief unget current character (read it again on next get) + + We implement unget by setting variable next_unget to true. The input is not + changed - we just simulate ungetting by modifying chars_read_total, + chars_read_current_line, and token_string. The next call to get() will + behave as if the unget character is read again. + */ + void unget() + { + next_unget = true; + + --position.chars_read_total; + + // in case we "unget" a newline, we have to also decrement the lines_read + if (position.chars_read_current_line == 0) + { + if (position.lines_read > 0) + { + --position.lines_read; + } + } + else + { + --position.chars_read_current_line; + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + JSON_ASSERT(!token_string.empty()); + token_string.pop_back(); + } + } + + /// add a character to token_buffer + void add(char_int_type c) + { + token_buffer.push_back(static_cast(c)); + } + + public: + ///////////////////// + // value getters + ///////////////////// + + /// return integer value + constexpr number_integer_t get_number_integer() const noexcept + { + return value_integer; + } + + /// return unsigned integer value + constexpr number_unsigned_t get_number_unsigned() const noexcept + { + return value_unsigned; + } + + /// return floating-point value + constexpr number_float_t get_number_float() const noexcept + { + return value_float; + } + + /// return current string value (implicitly resets the token; useful only once) + string_t& get_string() + { + return token_buffer; + } + + ///////////////////// + // diagnostics + ///////////////////// + + /// return position of last read token + constexpr position_t get_position() const noexcept + { + return position; + } + + /// return the last read token (for errors only). Will never contain EOF + /// (an arbitrary value that is not a valid char value, often -1), because + /// 255 may legitimately occur. May contain NUL, which should be escaped. + std::string get_token_string() const + { + // escape control characters + std::string result; + for (const auto c : token_string) + { + if (static_cast(c) <= '\x1F') + { + // escape control characters + std::array cs{{}}; + (std::snprintf)(cs.data(), cs.size(), "", static_cast(c)); + result += cs.data(); + } + else + { + // add character as is + result.push_back(static_cast(c)); + } + } + + return result; + } + + /// return syntax error message + JSON_HEDLEY_RETURNS_NON_NULL + constexpr const char* get_error_message() const noexcept + { + return error_message; + } + + ///////////////////// + // actual scanner + ///////////////////// + + /*! + @brief skip the UTF-8 byte order mark + @return true iff there is no BOM or the correct BOM has been skipped + */ + bool skip_bom() + { + if (get() == 0xEF) + { + // check if we completely parse the BOM + return get() == 0xBB && get() == 0xBF; + } + + // the first character is not the beginning of the BOM; unget it to + // process is later + unget(); + return true; + } + + void skip_whitespace() + { + do + { + get(); + } + while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); + } + + token_type scan() + { + // initially, skip the BOM + if (position.chars_read_total == 0 && !skip_bom()) + { + error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; + return token_type::parse_error; + } + + // read next character and ignore whitespace + skip_whitespace(); + + // ignore comments + while (ignore_comments && current == '/') + { + if (!scan_comment()) + { + return token_type::parse_error; + } + + // skip following whitespace + skip_whitespace(); + } + + switch (current) + { + // structural characters + case '[': + return token_type::begin_array; + case ']': + return token_type::end_array; + case '{': + return token_type::begin_object; + case '}': + return token_type::end_object; + case ':': + return token_type::name_separator; + case ',': + return token_type::value_separator; + + // literals + case 't': + { + std::array true_literal = {{'t', 'r', 'u', 'e'}}; + return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); + } + case 'f': + { + std::array false_literal = {{'f', 'a', 'l', 's', 'e'}}; + return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); + } + case 'n': + { + std::array null_literal = {{'n', 'u', 'l', 'l'}}; + return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); + } + + // string + case '\"': + return scan_string(); + + // number + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return scan_number(); + + // end of input (the null byte is needed when parsing from + // string literals) + case '\0': + case std::char_traits::eof(): + return token_type::end_of_input; + + // error + default: + error_message = "invalid literal"; + return token_type::parse_error; + } + } + + private: + /// input adapter + InputAdapterType ia; + + /// whether comments should be ignored (true) or signaled as errors (false) + const bool ignore_comments = false; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// whether the next get() call should just return current + bool next_unget = false; + + /// the start position of the current token + position_t position {}; + + /// raw input token string (for error messages) + std::vector token_string {}; + + /// buffer for variable-length tokens (numbers, strings) + string_t token_buffer {}; + + /// a description of occurred lexer errors + const char* error_message = ""; + + // number values + number_integer_t value_integer = 0; + number_unsigned_t value_unsigned = 0; + number_float_t value_float = 0; + + /// the decimal point + const char_int_type decimal_point_char = '.'; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // declval +#include // string + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +using null_function_t = decltype(std::declval().null()); + +template +using boolean_function_t = + decltype(std::declval().boolean(std::declval())); + +template +using number_integer_function_t = + decltype(std::declval().number_integer(std::declval())); + +template +using number_unsigned_function_t = + decltype(std::declval().number_unsigned(std::declval())); + +template +using number_float_function_t = decltype(std::declval().number_float( + std::declval(), std::declval())); + +template +using string_function_t = + decltype(std::declval().string(std::declval())); + +template +using binary_function_t = + decltype(std::declval().binary(std::declval())); + +template +using start_object_function_t = + decltype(std::declval().start_object(std::declval())); + +template +using key_function_t = + decltype(std::declval().key(std::declval())); + +template +using end_object_function_t = decltype(std::declval().end_object()); + +template +using start_array_function_t = + decltype(std::declval().start_array(std::declval())); + +template +using end_array_function_t = decltype(std::declval().end_array()); + +template +using parse_error_function_t = decltype(std::declval().parse_error( + std::declval(), std::declval(), + std::declval())); + +template +struct is_sax +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static constexpr bool value = + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value; +}; + +template +struct is_sax_static_asserts +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static_assert(is_detected_exact::value, + "Missing/invalid function: bool null()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_integer(number_integer_t)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool string(string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool binary(binary_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_object(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool key(string_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_object()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_array(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_array()"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool parse_error(std::size_t, const " + "std::string&, const exception&)"); +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/// how to treat CBOR tags +enum class cbor_tag_handler_t +{ + error, ///< throw a parse_error exception in case of a tag + ignore ///< ignore tags +}; + +/*! +@brief determine system byte order + +@return true if and only if system's byte order is little endian + +@note from https://stackoverflow.com/a/1001328/266378 +*/ +static inline bool little_endianess(int num = 1) noexcept +{ + return *reinterpret_cast(&num) == 1; +} + + +/////////////////// +// binary reader // +/////////////////// + +/*! +@brief deserialization of CBOR, MessagePack, and UBJSON values +*/ +template> +class binary_reader +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using json_sax_t = SAX; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + /*! + @brief create a binary reader + + @param[in] adapter input adapter to read from + */ + explicit binary_reader(InputAdapterType&& adapter) : ia(std::move(adapter)) + { + (void)detail::is_sax_static_asserts {}; + } + + // make class move-only + binary_reader(const binary_reader&) = delete; + binary_reader(binary_reader&&) = default; + binary_reader& operator=(const binary_reader&) = delete; + binary_reader& operator=(binary_reader&&) = default; + ~binary_reader() = default; + + /*! + @param[in] format the binary format to parse + @param[in] sax_ a SAX event processor + @param[in] strict whether to expect the input to be consumed completed + @param[in] tag_handler how to treat CBOR tags + + @return + */ + JSON_HEDLEY_NON_NULL(3) + bool sax_parse(const input_format_t format, + json_sax_t* sax_, + const bool strict = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + sax = sax_; + bool result = false; + + switch (format) + { + case input_format_t::bson: + result = parse_bson_internal(); + break; + + case input_format_t::cbor: + result = parse_cbor_internal(true, tag_handler); + break; + + case input_format_t::msgpack: + result = parse_msgpack_internal(); + break; + + case input_format_t::ubjson: + result = parse_ubjson_internal(); + break; + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + + // strict mode: next byte must be EOF + if (result && strict) + { + if (format == input_format_t::ubjson) + { + get_ignore_noop(); + } + else + { + get(); + } + + if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) + { + return sax->parse_error(chars_read, get_token_string(), + parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"))); + } + } + + return result; + } + + private: + ////////// + // BSON // + ////////// + + /*! + @brief Reads in a BSON-object and passes it to the SAX-parser. + @return whether a valid BSON-value was passed to the SAX parser + */ + bool parse_bson_internal() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) + { + return false; + } + + return sax->end_object(); + } + + /*! + @brief Parses a C-style string from the BSON input. + @param[in, out] result A reference to the string variable where the read + string is to be stored. + @return `true` if the \x00-byte indicating the end of the string was + encountered before the EOF; false` indicates an unexpected EOF. + */ + bool get_bson_cstr(string_t& result) + { + auto out = std::back_inserter(result); + while (true) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) + { + return false; + } + if (current == 0x00) + { + return true; + } + *out++ = static_cast(current); + } + } + + /*! + @brief Parses a zero-terminated string of length @a len from the BSON + input. + @param[in] len The length (including the zero-byte at the end) of the + string to be read. + @param[in, out] result A reference to the string variable where the read + string is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 1 + @return `true` if the string was successfully parsed + */ + template + bool get_bson_string(const NumberType len, string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"))); + } + + return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); + } + + /*! + @brief Parses a byte array input of length @a len from the BSON input. + @param[in] len The length of the byte array to be read. + @param[in, out] result A reference to the binary variable where the read + array is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 0 + @return `true` if the byte array was successfully parsed + */ + template + bool get_bson_binary(const NumberType len, binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 0)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"))); + } + + // All BSON binary values have a subtype + std::uint8_t subtype{}; + get_number(input_format_t::bson, subtype); + result.set_subtype(subtype); + + return get_binary(input_format_t::bson, len, result); + } + + /*! + @brief Read a BSON document element of the given @a element_type. + @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html + @param[in] element_type_parse_position The position in the input stream, + where the `element_type` was read. + @warning Not all BSON element types are supported yet. An unsupported + @a element_type will give rise to a parse_error.114: + Unsupported BSON record type 0x... + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_internal(const char_int_type element_type, + const std::size_t element_type_parse_position) + { + switch (element_type) + { + case 0x01: // double + { + double number{}; + return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); + } + + case 0x02: // string + { + std::int32_t len{}; + string_t value; + return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); + } + + case 0x03: // object + { + return parse_bson_internal(); + } + + case 0x04: // array + { + return parse_bson_array(); + } + + case 0x05: // binary + { + std::int32_t len{}; + binary_t value; + return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); + } + + case 0x08: // boolean + { + return sax->boolean(get() != 0); + } + + case 0x0A: // null + { + return sax->null(); + } + + case 0x10: // int32 + { + std::int32_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + case 0x12: // int64 + { + std::int64_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + default: // anything else not supported (yet) + { + std::array cr{{}}; + (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type)); + return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()))); + } + } + } + + /*! + @brief Read a BSON element list (as specified in the BSON-spec) + + The same binary layout is used for objects and arrays, hence it must be + indicated with the argument @a is_array which one is expected + (true --> array, false --> object). + + @param[in] is_array Determines if the element list being read is to be + treated as an object (@a is_array == false), or as an + array (@a is_array == true). + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_list(const bool is_array) + { + string_t key; + + while (auto element_type = get()) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) + { + return false; + } + + const std::size_t element_type_parse_position = chars_read; + if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) + { + return false; + } + + if (!is_array && !sax->key(key)) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) + { + return false; + } + + // get_bson_cstr only appends + key.clear(); + } + + return true; + } + + /*! + @brief Reads an array from the BSON input and passes it to the SAX-parser. + @return whether a valid BSON-array was passed to the SAX parser + */ + bool parse_bson_array() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) + { + return false; + } + + return sax->end_array(); + } + + ////////// + // CBOR // + ////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true) or whether the last read character should + be considered instead (false) + @param[in] tag_handler how CBOR tags should be treated + + @return whether a valid CBOR value was passed to the SAX parser + */ + bool parse_cbor_internal(const bool get_char, + const cbor_tag_handler_t tag_handler) + { + switch (get_char ? get() : current) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::cbor, "value"); + + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + return sax->number_unsigned(static_cast(current)); + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1A: // Unsigned integer (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1B: // Unsigned integer (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + return sax->number_integer(static_cast(0x20 - 1 - current)); + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) + - static_cast(number)); + } + + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: // Binary data (one-byte uint8_t for n follows) + case 0x59: // Binary data (two-byte uint16_t for n follow) + case 0x5A: // Binary data (four-byte uint32_t for n follow) + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + case 0x5F: // Binary data (indefinite length) + { + binary_t b; + return get_cbor_binary(b) && sax->binary(b); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + case 0x7F: // UTF-8 string (indefinite length) + { + string_t s; + return get_cbor_string(s) && sax->string(s); + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0x98: // array (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9A: // array (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9B: // array (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9F: // array (indefinite length) + return get_cbor_array(std::size_t(-1), tag_handler); + + // map (0x00..0x17 pairs of data items follow) + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0xB8: // map (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xB9: // map (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBA: // map (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBB: // map (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBF: // map (indefinite length) + return get_cbor_object(std::size_t(-1), tag_handler); + + case 0xC6: // tagged item + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD8: // tagged item (1 bytes follow) + case 0xD9: // tagged item (2 bytes follow) + case 0xDA: // tagged item (4 bytes follow) + case 0xDB: // tagged item (8 bytes follow) + { + switch (tag_handler) + { + case cbor_tag_handler_t::error: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"))); + } + + case cbor_tag_handler_t::ignore: + { + switch (current) + { + case 0xD8: + { + std::uint8_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xD9: + { + std::uint16_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xDA: + { + std::uint32_t len{}; + get_number(input_format_t::cbor, len); + break; + } + case 0xDB: + { + std::uint64_t len{}; + get_number(input_format_t::cbor, len); + break; + } + default: + break; + } + return parse_cbor_internal(true, tag_handler); + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + } + + case 0xF4: // false + return sax->boolean(false); + + case 0xF5: // true + return sax->boolean(true); + + case 0xF6: // null + return sax->null(); + + case 0xF9: // Half-Precision Float (two-byte IEEE 754) + { + const auto byte1_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + const auto byte2_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + + const auto byte1 = static_cast(byte1_raw); + const auto byte2 = static_cast(byte2_raw); + + // code from RFC 7049, Appendix D, Figure 3: + // As half-precision floating-point numbers were only added + // to IEEE 754 in 2008, today's programming platforms often + // still only have limited support for them. It is very + // easy to include at least decoding support for them even + // without such support. An example of a small decoder for + // half-precision floating-point numbers in the C language + // is shown in Fig. 3. + const auto half = static_cast((byte1 << 8u) + byte2); + const double val = [&half] + { + const int exp = (half >> 10u) & 0x1Fu; + const unsigned int mant = half & 0x3FFu; + JSON_ASSERT(0 <= exp&& exp <= 32); + JSON_ASSERT(mant <= 1024); + switch (exp) + { + case 0: + return std::ldexp(mant, -24); + case 31: + return (mant == 0) + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + default: + return std::ldexp(mant + 1024, exp - 25); + } + }(); + return sax->number_float((half & 0x8000u) != 0 + ? static_cast(-val) + : static_cast(val), ""); + } + + case 0xFA: // Single-Precision Float (four-byte IEEE 754) + { + float number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + case 0xFB: // Double-Precision Float (eight-byte IEEE 754) + { + double number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + default: // anything else (0xFF is handled inside the other types) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"))); + } + } + } + + /*! + @brief reads a CBOR string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + Additionally, CBOR's strings with indefinite lengths are supported. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_cbor_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) + { + return false; + } + + switch (current) + { + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7F: // UTF-8 string (indefinite length) + { + while (get() != 0xFF) + { + string_t chunk; + if (!get_cbor_string(chunk)) + { + return false; + } + result.append(chunk); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"))); + } + } + } + + /*! + @brief reads a CBOR byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into the byte array. + Additionally, CBOR's byte arrays with indefinite lengths are supported. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_cbor_binary(binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) + { + return false; + } + + switch (current) + { + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + { + return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x58: // Binary data (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x59: // Binary data (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5A: // Binary data (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5F: // Binary data (indefinite length) + { + while (get() != 0xFF) + { + binary_t chunk; + if (!get_cbor_binary(chunk)) + { + return false; + } + result.insert(result.end(), chunk.begin(), chunk.end()); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"))); + } + } + } + + /*! + @param[in] len the length of the array or std::size_t(-1) for an + array of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether array creation completed + */ + bool get_cbor_array(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + if (len != std::size_t(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) + { + return false; + } + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object or std::size_t(-1) for an + object of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether object creation completed + */ + bool get_cbor_object(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + if (len != std::size_t(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + + return sax->end_object(); + } + + ///////////// + // MsgPack // + ///////////// + + /*! + @return whether a valid MessagePack value was passed to the SAX parser + */ + bool parse_msgpack_internal() + { + switch (get()) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::msgpack, "value"); + + // positive fixint + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1A: + case 0x1B: + case 0x1C: + case 0x1D: + case 0x1E: + case 0x1F: + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5C: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + return sax->number_unsigned(static_cast(current)); + + // fixmap + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); + + // fixarray + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + case 0x98: + case 0x99: + case 0x9A: + case 0x9B: + case 0x9C: + case 0x9D: + case 0x9E: + case 0x9F: + return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); + + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + case 0xD9: // str 8 + case 0xDA: // str 16 + case 0xDB: // str 32 + { + string_t s; + return get_msgpack_string(s) && sax->string(s); + } + + case 0xC0: // nil + return sax->null(); + + case 0xC2: // false + return sax->boolean(false); + + case 0xC3: // true + return sax->boolean(true); + + case 0xC4: // bin 8 + case 0xC5: // bin 16 + case 0xC6: // bin 32 + case 0xC7: // ext 8 + case 0xC8: // ext 16 + case 0xC9: // ext 32 + case 0xD4: // fixext 1 + case 0xD5: // fixext 2 + case 0xD6: // fixext 4 + case 0xD7: // fixext 8 + case 0xD8: // fixext 16 + { + binary_t b; + return get_msgpack_binary(b) && sax->binary(b); + } + + case 0xCA: // float 32 + { + float number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCB: // float 64 + { + double number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCC: // uint 8 + { + std::uint8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCD: // uint 16 + { + std::uint16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCE: // uint 32 + { + std::uint32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCF: // uint 64 + { + std::uint64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xD0: // int 8 + { + std::int8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD1: // int 16 + { + std::int16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD2: // int 32 + { + std::int32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD3: // int 64 + { + std::int64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xDC: // array 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDD: // array 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDE: // map 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + case 0xDF: // map 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + // negative fixint + case 0xE0: + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xED: + case 0xEE: + case 0xEF: + case 0xF0: + case 0xF1: + case 0xF2: + case 0xF3: + case 0xF4: + case 0xF5: + case 0xF6: + case 0xF7: + case 0xF8: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + return sax->number_integer(static_cast(current)); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"))); + } + } + } + + /*! + @brief reads a MessagePack string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_msgpack_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) + { + return false; + } + + switch (current) + { + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + { + return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); + } + + case 0xD9: // str 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDA: // str 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDB: // str 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"))); + } + } + } + + /*! + @brief reads a MessagePack byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into a byte array. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_msgpack_binary(binary_t& result) + { + // helper function to set the subtype + auto assign_and_return_true = [&result](std::int8_t subtype) + { + result.set_subtype(static_cast(subtype)); + return true; + }; + + switch (current) + { + case 0xC4: // bin 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC5: // bin 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC6: // bin 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC7: // ext 8 + { + std::uint8_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC8: // ext 16 + { + std::uint16_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC9: // ext 32 + { + std::uint32_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xD4: // fixext 1 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 1, result) && + assign_and_return_true(subtype); + } + + case 0xD5: // fixext 2 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 2, result) && + assign_and_return_true(subtype); + } + + case 0xD6: // fixext 4 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 4, result) && + assign_and_return_true(subtype); + } + + case 0xD7: // fixext 8 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 8, result) && + assign_and_return_true(subtype); + } + + case 0xD8: // fixext 16 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 16, result) && + assign_and_return_true(subtype); + } + + default: // LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + /*! + @param[in] len the length of the array + @return whether array creation completed + */ + bool get_msgpack_array(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object + @return whether object creation completed + */ + bool get_msgpack_object(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + key.clear(); + } + + return sax->end_object(); + } + + //////////// + // UBJSON // + //////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether a valid UBJSON value was passed to the SAX parser + */ + bool parse_ubjson_internal(const bool get_char = true) + { + return get_ubjson_value(get_char ? get_ignore_noop() : current); + } + + /*! + @brief reads a UBJSON string + + This function is either called after reading the 'S' byte explicitly + indicating a string, or in case of an object key where the 'S' byte can be + left out. + + @param[out] result created string + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether string creation completed + */ + bool get_ubjson_string(string_t& result, const bool get_char = true) + { + if (get_char) + { + get(); // TODO(niels): may we ignore N here? + } + + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + + switch (current) + { + case 'U': + { + std::uint8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'i': + { + std::int8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'I': + { + std::int16_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'l': + { + std::int32_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'L': + { + std::int64_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + default: + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"))); + } + } + + /*! + @param[out] result determined size + @return whether size determination completed + */ + bool get_ubjson_size_value(std::size_t& result) + { + switch (get_ignore_noop()) + { + case 'U': + { + std::uint8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'i': + { + std::int8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'I': + { + std::int16_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'l': + { + std::int32_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'L': + { + std::int64_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"))); + } + } + } + + /*! + @brief determine the type and size for a container + + In the optimized UBJSON format, a type and a size can be provided to allow + for a more compact representation. + + @param[out] result pair of the size and the type + + @return whether pair creation completed + */ + bool get_ubjson_size_type(std::pair& result) + { + result.first = string_t::npos; // size + result.second = 0; // type + + get_ignore_noop(); + + if (current == '$') + { + result.second = get(); // must not ignore 'N', because 'N' maybe the type + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) + { + return false; + } + + get_ignore_noop(); + if (JSON_HEDLEY_UNLIKELY(current != '#')) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"))); + } + + return get_ubjson_size_value(result.first); + } + + if (current == '#') + { + return get_ubjson_size_value(result.first); + } + + return true; + } + + /*! + @param prefix the previously read or set type prefix + @return whether value creation completed + */ + bool get_ubjson_value(const char_int_type prefix) + { + switch (prefix) + { + case std::char_traits::eof(): // EOF + return unexpect_eof(input_format_t::ubjson, "value"); + + case 'T': // true + return sax->boolean(true); + case 'F': // false + return sax->boolean(false); + + case 'Z': // null + return sax->null(); + + case 'U': + { + std::uint8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); + } + + case 'i': + { + std::int8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'I': + { + std::int16_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'l': + { + std::int32_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'L': + { + std::int64_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'd': + { + float number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'D': + { + double number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'H': + { + return get_ubjson_high_precision_number(); + } + + case 'C': // char + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(current > 127)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"))); + } + string_t s(1, static_cast(current)); + return sax->string(s); + } + + case 'S': // string + { + string_t s; + return get_ubjson_string(s) && sax->string(s); + } + + case '[': // array + return get_ubjson_array(); + + case '{': // object + return get_ubjson_object(); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"))); + } + } + } + + /*! + @return whether array creation completed + */ + bool get_ubjson_array() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + if (size_and_type.second != 'N') + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + } + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + while (current != ']') + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) + { + return false; + } + get_ignore_noop(); + } + } + + return sax->end_array(); + } + + /*! + @return whether object creation completed + */ + bool get_ubjson_object() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + string_t key; + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + key.clear(); + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + key.clear(); + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + while (current != '}') + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + get_ignore_noop(); + key.clear(); + } + } + + return sax->end_object(); + } + + // Note, no reader for UBJSON binary types is implemented because they do + // not exist + + bool get_ubjson_high_precision_number() + { + // get size of following number string + std::size_t size{}; + auto res = get_ubjson_size_value(size); + if (JSON_HEDLEY_UNLIKELY(!res)) + { + return res; + } + + // get number string + std::vector number_vector; + for (std::size_t i = 0; i < size; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) + { + return false; + } + number_vector.push_back(static_cast(current)); + } + + // parse number string + auto number_ia = detail::input_adapter(std::forward(number_vector)); + auto number_lexer = detail::lexer(std::move(number_ia), false); + const auto result_number = number_lexer.scan(); + const auto number_string = number_lexer.get_token_string(); + const auto result_remainder = number_lexer.scan(); + + using token_type = typename detail::lexer_base::token_type; + + if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) + { + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"))); + } + + switch (result_number) + { + case token_type::value_integer: + return sax->number_integer(number_lexer.get_number_integer()); + case token_type::value_unsigned: + return sax->number_unsigned(number_lexer.get_number_unsigned()); + case token_type::value_float: + return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); + default: + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"))); + } + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /*! + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a -'ve valued + `std::char_traits::eof()` in that case. + + @return character read from the input + */ + char_int_type get() + { + ++chars_read; + return current = ia.get_character(); + } + + /*! + @return character read from the input after ignoring all 'N' entries + */ + char_int_type get_ignore_noop() + { + do + { + get(); + } + while (current == 'N'); + + return current; + } + + /* + @brief read a number from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[out] result number of type @a NumberType + + @return whether conversion completed + + @note This function needs to respect the system's endianess, because + bytes in CBOR, MessagePack, and UBJSON are stored in network order + (big endian) and therefore need reordering on little endian systems. + */ + template + bool get_number(const input_format_t format, NumberType& result) + { + // step 1: read input into array with system's byte order + std::array vec; + for (std::size_t i = 0; i < sizeof(NumberType); ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) + { + return false; + } + + // reverse byte order prior to conversion if necessary + if (is_little_endian != InputIsLittleEndian) + { + vec[sizeof(NumberType) - i - 1] = static_cast(current); + } + else + { + vec[i] = static_cast(current); // LCOV_EXCL_LINE + } + } + + // step 2: convert array into number of type T and return + std::memcpy(&result, vec.data(), sizeof(NumberType)); + return true; + } + + /*! + @brief create a string by reading characters from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of characters to read + @param[out] result string created by reading @a len bytes + + @return whether string creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of string memory. + */ + template + bool get_string(const input_format_t format, + const NumberType len, + string_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + }; + return success; + } + + /*! + @brief create a byte array by reading bytes from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of bytes to read + @param[out] result byte array created by reading @a len bytes + + @return whether byte array creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of memory. + */ + template + bool get_binary(const input_format_t format, + const NumberType len, + binary_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @param[in] format the current format (for diagnostics) + @param[in] context further context information (for diagnostics) + @return whether the last read character is not EOF + */ + JSON_HEDLEY_NON_NULL(3) + bool unexpect_eof(const input_format_t format, const char* context) const + { + if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) + { + return sax->parse_error(chars_read, "", + parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context))); + } + return true; + } + + /*! + @return a string representation of the last read byte + */ + std::string get_token_string() const + { + std::array cr{{}}; + (std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current)); + return std::string{cr.data()}; + } + + /*! + @param[in] format the current format + @param[in] detail a detailed error message + @param[in] context further context information + @return a message string to use in the parse_error exceptions + */ + std::string exception_message(const input_format_t format, + const std::string& detail, + const std::string& context) const + { + std::string error_msg = "syntax error while parsing "; + + switch (format) + { + case input_format_t::cbor: + error_msg += "CBOR"; + break; + + case input_format_t::msgpack: + error_msg += "MessagePack"; + break; + + case input_format_t::ubjson: + error_msg += "UBJSON"; + break; + + case input_format_t::bson: + error_msg += "BSON"; + break; + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + + return error_msg + " " + context + ": " + detail; + } + + private: + /// input adapter + InputAdapterType ia; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// the number of characters read + std::size_t chars_read = 0; + + /// whether we can assume little endianess + const bool is_little_endian = little_endianess(); + + /// the SAX parser + json_sax_t* sax = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // isfinite +#include // uint8_t +#include // function +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////// +// parser // +//////////// + +enum class parse_event_t : uint8_t +{ + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value +}; + +template +using parser_callback_t = + std::function; + +/*! +@brief syntax analysis + +This class implements a recursive descent parser. +*/ +template +class parser +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using lexer_t = lexer; + using token_type = typename lexer_t::token_type; + + public: + /// a parser reading from an input adapter + explicit parser(InputAdapterType&& adapter, + const parser_callback_t cb = nullptr, + const bool allow_exceptions_ = true, + const bool skip_comments = false) + : callback(cb) + , m_lexer(std::move(adapter), skip_comments) + , allow_exceptions(allow_exceptions_) + { + // read first token + get_token(); + } + + /*! + @brief public parser interface + + @param[in] strict whether to expect the last token to be EOF + @param[in,out] result parsed JSON value + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + void parse(const bool strict, BasicJsonType& result) + { + if (callback) + { + json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); + sax_parse_internal(&sdp); + result.assert_invariant(); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"))); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + + // set top-level value to null if it was discarded by the callback + // function + if (result.is_discarded()) + { + result = nullptr; + } + } + else + { + json_sax_dom_parser sdp(result, allow_exceptions); + sax_parse_internal(&sdp); + result.assert_invariant(); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"))); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + } + } + + /*! + @brief public accept interface + + @param[in] strict whether to expect the last token to be EOF + @return whether the input is a proper JSON text + */ + bool accept(const bool strict = true) + { + json_sax_acceptor sax_acceptor; + return sax_parse(&sax_acceptor, strict); + } + + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse(SAX* sax, const bool strict = true) + { + (void)detail::is_sax_static_asserts {}; + const bool result = sax_parse_internal(sax); + + // strict mode: next byte must be EOF + if (result && strict && (get_token() != token_type::end_of_input)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"))); + } + + return result; + } + + private: + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse_internal(SAX* sax) + { + // stack to remember the hierarchy of structured values we are parsing + // true = array; false = object + std::vector states; + // value to avoid a goto (see comment where set to true) + bool skip_to_state_evaluation = false; + + while (true) + { + if (!skip_to_state_evaluation) + { + // invariant: get_token() was called before each iteration + switch (last_token) + { + case token_type::begin_object: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(std::size_t(-1)))) + { + return false; + } + + // closing } -> we are done + if (get_token() == token_type::end_object) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + break; + } + + // parse key + if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::value_string, "object key"))); + } + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::name_separator, "object separator"))); + } + + // remember we are now inside an object + states.push_back(false); + + // parse values + get_token(); + continue; + } + + case token_type::begin_array: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(std::size_t(-1)))) + { + return false; + } + + // closing ] -> we are done + if (get_token() == token_type::end_array) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + break; + } + + // remember we are now inside an array + states.push_back(true); + + // parse values (no need to call get_token) + continue; + } + + case token_type::value_float: + { + const auto res = m_lexer.get_number_float(); + + if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) + { + return false; + } + + break; + } + + case token_type::literal_false: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) + { + return false; + } + break; + } + + case token_type::literal_null: + { + if (JSON_HEDLEY_UNLIKELY(!sax->null())) + { + return false; + } + break; + } + + case token_type::literal_true: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) + { + return false; + } + break; + } + + case token_type::value_integer: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) + { + return false; + } + break; + } + + case token_type::value_string: + { + if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) + { + return false; + } + break; + } + + case token_type::value_unsigned: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) + { + return false; + } + break; + } + + case token_type::parse_error: + { + // using "uninitialized" to avoid "expected" message + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::uninitialized, "value"))); + } + + default: // the last token was unexpected + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::literal_or_value, "value"))); + } + } + } + else + { + skip_to_state_evaluation = false; + } + + // we reached this line after we successfully parsed a value + if (states.empty()) + { + // empty stack: we reached the end of the hierarchy: done + return true; + } + + if (states.back()) // array + { + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse a new value + get_token(); + continue; + } + + // closing ] + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + + // We are done with this array. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_array, "array"))); + } + else // object + { + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse key + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::value_string, "object key"))); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::name_separator, "object separator"))); + } + + // parse values + get_token(); + continue; + } + + // closing } + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + + // We are done with this object. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_object, "object"))); + } + } + } + + /// get next token from lexer + token_type get_token() + { + return last_token = m_lexer.scan(); + } + + std::string exception_message(const token_type expected, const std::string& context) + { + std::string error_msg = "syntax error "; + + if (!context.empty()) + { + error_msg += "while parsing " + context + " "; + } + + error_msg += "- "; + + if (last_token == token_type::parse_error) + { + error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); + } + + if (expected != token_type::uninitialized) + { + error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); + } + + return error_msg; + } + + private: + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + token_type last_token = token_type::uninitialized; + /// the lexer + lexer_t m_lexer; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +#include // ptrdiff_t +#include // numeric_limits + +namespace nlohmann +{ +namespace detail +{ +/* +@brief an iterator for primitive JSON types + +This class models an iterator for primitive JSON types (boolean, number, +string). It's only purpose is to allow the iterator/const_iterator classes +to "iterate" over primitive values. Internally, the iterator is modeled by +a `difference_type` variable. Value begin_value (`0`) models the begin, +end_value (`1`) models past the end. +*/ +class primitive_iterator_t +{ + private: + using difference_type = std::ptrdiff_t; + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + /// iterator as signed integer type + difference_type m_it = (std::numeric_limits::min)(); + + public: + constexpr difference_type get_value() const noexcept + { + return m_it; + } + + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return m_it == begin_value; + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return m_it == end_value; + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + primitive_iterator_t operator+(difference_type n) noexcept + { + auto result = *this; + result += n; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + primitive_iterator_t& operator++() noexcept + { + ++m_it; + return *this; + } + + primitive_iterator_t const operator++(int) noexcept + { + auto result = *this; + ++m_it; + return result; + } + + primitive_iterator_t& operator--() noexcept + { + --m_it; + return *this; + } + + primitive_iterator_t const operator--(int) noexcept + { + auto result = *this; + --m_it; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) noexcept + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) noexcept + { + m_it -= n; + return *this; + } +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/*! +@brief an iterator value + +@note This structure could easily be a union, but MSVC currently does not allow +unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. +*/ +template struct internal_iterator +{ + /// iterator for JSON objects + typename BasicJsonType::object_t::iterator object_iterator {}; + /// iterator for JSON arrays + typename BasicJsonType::array_t::iterator array_iterator {}; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next +#include // conditional, is_const, remove_const + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// forward declare, to be able to friend it later on +template class iteration_proxy; +template class iteration_proxy_value; + +/*! +@brief a template for a bidirectional iterator for the @ref basic_json class +This class implements a both iterators (iterator and const_iterator) for the +@ref basic_json class. +@note An iterator is called *initialized* when a pointer to a JSON value has + been set (e.g., by a constructor or a copy assignment). If the iterator is + default-constructed, it is *uninitialized* and most methods are undefined. + **The library uses assertions to detect calls on uninitialized iterators.** +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +@since version 1.0.0, simplified in version 2.0.9, change to bidirectional + iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) +*/ +template +class iter_impl +{ + /// allow basic_json to access private members + friend iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; + friend BasicJsonType; + friend iteration_proxy; + friend iteration_proxy_value; + + using object_t = typename BasicJsonType::object_t; + using array_t = typename BasicJsonType::array_t; + // make sure BasicJsonType is basic_json or const basic_json + static_assert(is_basic_json::type>::value, + "iter_impl only accepts (const) basic_json"); + + public: + + /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. + /// The C++ Standard has never required user-defined iterators to derive from std::iterator. + /// A user-defined iterator should provide publicly accessible typedefs named + /// iterator_category, value_type, difference_type, pointer, and reference. + /// Note that value_type is required to be non-const, even for constant iterators. + using iterator_category = std::bidirectional_iterator_tag; + + /// the type of the values when the iterator is dereferenced + using value_type = typename BasicJsonType::value_type; + /// a type to represent differences between iterators + using difference_type = typename BasicJsonType::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename BasicJsonType::const_pointer, + typename BasicJsonType::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = + typename std::conditional::value, + typename BasicJsonType::const_reference, + typename BasicJsonType::reference>::type; + + /// default constructor + iter_impl() = default; + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept : m_object(object) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /*! + @note The conventional copy constructor and copy assignment are implicitly + defined. Combined with the following converting constructor and + assignment, they support: (1) copy from iterator to iterator, (2) + copy from const iterator to const iterator, and (3) conversion from + iterator to const iterator. However conversion from const iterator + to iterator is not defined. + */ + + /*! + @brief const copy constructor + @param[in] other const iterator to copy from + @note This copy constructor had to be defined explicitly to circumvent a bug + occurring on msvc v19.0 compiler (VS 2015) debug build. For more + information refer to: https://github.com/nlohmann/json/issues/1608 + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl& other) noexcept + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + /*! + @brief converting constructor + @param[in] other non-const iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl::type>& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other non-const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl::type>& other) noexcept + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + private: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator++(int) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, 1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, 1); + break; + } + + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator--(int) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, -1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator==(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + return (m_it.object_iterator == other.m_it.object_iterator); + + case value_t::array: + return (m_it.array_iterator == other.m_it.array_iterator); + + default: + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator!=(const iter_impl& other) const + { + return !operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); + + case value_t::array: + return (m_it.array_iterator < other.m_it.array_iterator); + + default: + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return !other.operator < (*this); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return !operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return !operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); + + case value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief addition of distance and iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + friend iter_impl operator+(difference_type i, const iter_impl& it) + { + auto result = it; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); + + case value_t::array: + return m_it.array_iterator - other.m_it.array_iterator; + + default: + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); + + case value_t::array: + return *std::next(m_it.array_iterator, n); + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value")); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + const typename object_t::key_type& key() const + { + JSON_ASSERT(m_object != nullptr); + + if (JSON_HEDLEY_LIKELY(m_object->is_object())) + { + return m_it.object_iterator->first; + } + + JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + private: + /// associated JSON instance + pointer m_object = nullptr; + /// the actual iterator of the associated instance + internal_iterator::type> m_it {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // ptrdiff_t +#include // reverse_iterator +#include // declval + +namespace nlohmann +{ +namespace detail +{ +////////////////////// +// reverse_iterator // +////////////////////// + +/*! +@brief a template for a reverse iterator class + +@tparam Base the base iterator type to reverse. Valid types are @ref +iterator (to create @ref reverse_iterator) and @ref const_iterator (to +create @ref const_reverse_iterator). + +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): + It is possible to write to the pointed-to element (only if @a Base is + @ref iterator). + +@since version 1.0.0 +*/ +template +class json_reverse_iterator : public std::reverse_iterator +{ + public: + using difference_type = std::ptrdiff_t; + /// shortcut to the reverse iterator adapter + using base_iterator = std::reverse_iterator; + /// the reference type for the pointed-to element + using reference = typename Base::reference; + + /// create reverse iterator from iterator + explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept + : base_iterator(it) {} + + /// create reverse iterator from base class + explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} + + /// post-increment (it++) + json_reverse_iterator const operator++(int) + { + return static_cast(base_iterator::operator++(1)); + } + + /// pre-increment (++it) + json_reverse_iterator& operator++() + { + return static_cast(base_iterator::operator++()); + } + + /// post-decrement (it--) + json_reverse_iterator const operator--(int) + { + return static_cast(base_iterator::operator--(1)); + } + + /// pre-decrement (--it) + json_reverse_iterator& operator--() + { + return static_cast(base_iterator::operator--()); + } + + /// add to iterator + json_reverse_iterator& operator+=(difference_type i) + { + return static_cast(base_iterator::operator+=(i)); + } + + /// add to iterator + json_reverse_iterator operator+(difference_type i) const + { + return static_cast(base_iterator::operator+(i)); + } + + /// subtract from iterator + json_reverse_iterator operator-(difference_type i) const + { + return static_cast(base_iterator::operator-(i)); + } + + /// return difference + difference_type operator-(const json_reverse_iterator& other) const + { + return base_iterator(*this) - base_iterator(other); + } + + /// access to successor + reference operator[](difference_type n) const + { + return *(this->operator+(n)); + } + + /// return the key of an object iterator + auto key() const -> decltype(std::declval().key()) + { + auto it = --this->base(); + return it.key(); + } + + /// return the value of an iterator + reference value() const + { + auto it = --this->base(); + return it.operator * (); + } +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // all_of +#include // isdigit +#include // max +#include // accumulate +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +template +class json_pointer +{ + // allow basic_json to access private members + NLOHMANN_BASIC_JSON_TPL_DECLARATION + friend class basic_json; + + public: + /*! + @brief create JSON pointer + + Create a JSON pointer according to the syntax described in + [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). + + @param[in] s string representing the JSON pointer; if omitted, the empty + string is assumed which references the whole JSON value + + @throw parse_error.107 if the given JSON pointer @a s is nonempty and does + not begin with a slash (`/`); see example below + + @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is + not followed by `0` (representing `~`) or `1` (representing `/`); see + example below + + @liveexample{The example shows the construction several valid JSON pointers + as well as the exceptional behavior.,json_pointer} + + @since version 2.0.0 + */ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /*! + @brief return a string representation of the JSON pointer + + @invariant For each JSON pointer `ptr`, it holds: + @code {.cpp} + ptr == json_pointer(ptr.to_string()); + @endcode + + @return a string representation of the JSON pointer + + @liveexample{The example shows the result of `to_string`.,json_pointer__to_string} + + @since version 2.0.0 + */ + std::string to_string() const + { + return std::accumulate(reference_tokens.begin(), reference_tokens.end(), + std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + escape(b); + }); + } + + /// @copydoc to_string() + operator std::string() const + { + return to_string(); + } + + /*! + @brief append another JSON pointer at the end of this JSON pointer + + @param[in] ptr JSON pointer to append + @return JSON pointer with @a ptr appended + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Linear in the length of @a ptr. + + @sa @ref operator/=(std::string) to append a reference token + @sa @ref operator/=(std::size_t) to append an array index + @sa @ref operator/(const json_pointer&, const json_pointer&) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(const json_pointer& ptr) + { + reference_tokens.insert(reference_tokens.end(), + ptr.reference_tokens.begin(), + ptr.reference_tokens.end()); + return *this; + } + + /*! + @brief append an unescaped reference token at the end of this JSON pointer + + @param[in] token reference token to append + @return JSON pointer with @a token appended without escaping @a token + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Amortized constant. + + @sa @ref operator/=(const json_pointer&) to append a JSON pointer + @sa @ref operator/=(std::size_t) to append an array index + @sa @ref operator/(const json_pointer&, std::size_t) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(std::string token) + { + push_back(std::move(token)); + return *this; + } + + /*! + @brief append an array index at the end of this JSON pointer + + @param[in] array_idx array index to append + @return JSON pointer with @a array_idx appended + + @liveexample{The example shows the usage of `operator/=`.,json_pointer__operator_add} + + @complexity Amortized constant. + + @sa @ref operator/=(const json_pointer&) to append a JSON pointer + @sa @ref operator/=(std::string) to append a reference token + @sa @ref operator/(const json_pointer&, std::string) for a binary operator + + @since version 3.6.0 + */ + json_pointer& operator/=(std::size_t array_idx) + { + return *this /= std::to_string(array_idx); + } + + /*! + @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer + + @param[in] lhs JSON pointer + @param[in] rhs JSON pointer + @return a new JSON pointer with @a rhs appended to @a lhs + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a lhs and @a rhs. + + @sa @ref operator/=(const json_pointer&) to append a JSON pointer + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& lhs, + const json_pointer& rhs) + { + return json_pointer(lhs) /= rhs; + } + + /*! + @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer + + @param[in] ptr JSON pointer + @param[in] token reference token + @return a new JSON pointer with unescaped @a token appended to @a ptr + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a ptr. + + @sa @ref operator/=(std::string) to append a reference token + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& ptr, std::string token) + { + return json_pointer(ptr) /= std::move(token); + } + + /*! + @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer + + @param[in] ptr JSON pointer + @param[in] array_idx array index + @return a new JSON pointer with @a array_idx appended to @a ptr + + @liveexample{The example shows the usage of `operator/`.,json_pointer__operator_add_binary} + + @complexity Linear in the length of @a ptr. + + @sa @ref operator/=(std::size_t) to append an array index + + @since version 3.6.0 + */ + friend json_pointer operator/(const json_pointer& ptr, std::size_t array_idx) + { + return json_pointer(ptr) /= array_idx; + } + + /*! + @brief returns the parent of this JSON pointer + + @return parent of this JSON pointer; in case this JSON pointer is the root, + the root itself is returned + + @complexity Linear in the length of the JSON pointer. + + @liveexample{The example shows the result of `parent_pointer` for different + JSON Pointers.,json_pointer__parent_pointer} + + @since version 3.6.0 + */ + json_pointer parent_pointer() const + { + if (empty()) + { + return *this; + } + + json_pointer res = *this; + res.pop_back(); + return res; + } + + /*! + @brief remove last reference token + + @pre not `empty()` + + @liveexample{The example shows the usage of `pop_back`.,json_pointer__pop_back} + + @complexity Constant. + + @throw out_of_range.405 if JSON pointer has no parent + + @since version 3.6.0 + */ + void pop_back() + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); + } + + reference_tokens.pop_back(); + } + + /*! + @brief return last reference token + + @pre not `empty()` + @return last reference token + + @liveexample{The example shows the usage of `back`.,json_pointer__back} + + @complexity Constant. + + @throw out_of_range.405 if JSON pointer has no parent + + @since version 3.6.0 + */ + const std::string& back() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); + } + + return reference_tokens.back(); + } + + /*! + @brief append an unescaped token at the end of the reference pointer + + @param[in] token token to add + + @complexity Amortized constant. + + @liveexample{The example shows the result of `push_back` for different + JSON Pointers.,json_pointer__push_back} + + @since version 3.6.0 + */ + void push_back(const std::string& token) + { + reference_tokens.push_back(token); + } + + /// @copydoc push_back(const std::string&) + void push_back(std::string&& token) + { + reference_tokens.push_back(std::move(token)); + } + + /*! + @brief return whether pointer points to the root document + + @return true iff the JSON pointer points to the root document + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example shows the result of `empty` for different JSON + Pointers.,json_pointer__empty} + + @since version 3.6.0 + */ + bool empty() const noexcept + { + return reference_tokens.empty(); + } + + private: + /*! + @param[in] s reference token to be converted into an array index + + @return integer representation of @a s + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index begins not with a digit + @throw out_of_range.404 if string @a s could not be converted to an integer + @throw out_of_range.410 if an array index exceeds size_type + */ + static typename BasicJsonType::size_type array_index(const std::string& s) + { + using size_type = typename BasicJsonType::size_type; + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) + { + JSON_THROW(detail::parse_error::create(106, 0, + "array index '" + s + + "' must not begin with '0'")); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) + { + JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number")); + } + + std::size_t processed_chars = 0; + unsigned long long res = 0; + JSON_TRY + { + res = std::stoull(s, &processed_chars); + } + JSON_CATCH(std::out_of_range&) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); + } + + // check if the string was completely read + if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); + } + + // only triggered on special platforms (like 32bit), see also + // https://github.com/nlohmann/json/pull/2203 + if (res >= static_cast((std::numeric_limits::max)())) + { + JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type")); // LCOV_EXCL_LINE + } + + return static_cast(res); + } + + json_pointer top() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + + @throw parse_error.109 if array index is not a number + @throw type_error.313 if value cannot be unflattened + */ + BasicJsonType& get_and_create(BasicJsonType& j) const + { + auto result = &j; + + // in case no reference tokens exist, return a reference to the JSON value + // j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->type()) + { + case detail::value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case detail::value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + // create an entry in the array + result = &result->operator[](array_index(reference_token)); + break; + } + + /* + The following code is only reached if there exists a reference + token _and_ the current value is primitive. In this case, we have + an error situation, because primitive values may only occur as + single value; that is, with an empty list of reference tokens. + */ + default: + JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); + } + } + + return *result; + } + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries to + create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_unchecked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->is_null()) + { + // check if reference token is a number + const bool nums = + std::all_of(reference_token.begin(), reference_token.end(), + [](const unsigned char x) + { + return std::isdigit(x); + }); + + // change value to array for numbers or "-" or to object otherwise + *ptr = (nums || reference_token == "-") + ? detail::value_t::array + : detail::value_t::object; + } + + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + ptr = &ptr->operator[](array_index(reference_token)); + } + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_checked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + + return *ptr; + } + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" cannot be used for const access + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // use unchecked array access + ptr = &ptr->operator[](array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_checked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range")); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + */ + bool contains(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + if (!ptr->contains(reference_token)) + { + // we did not find the key in the object + return false; + } + + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) + { + // invalid char + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) + { + if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) + { + // first char should be between '1' and '9' + return false; + } + for (std::size_t i = 1; i < reference_token.size(); i++) + { + if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) + { + // other char should be between '0' and '9' + return false; + } + } + } + + const auto idx = array_index(reference_token); + if (idx >= ptr->size()) + { + // index out of range + return false; + } + + ptr = &ptr->operator[](idx); + break; + } + + default: + { + // we do not expect primitive values if there is still a + // reference token to process + return false; + } + } + } + + // no reference token left means we found a primitive value + return true; + } + + /*! + @brief split the string input to reference tokens + + @note This function is only called by the json_pointer constructor. + All exceptions below are documented there. + + @throw parse_error.107 if the pointer is not empty or begins with '/' + @throw parse_error.108 if character '~' is not followed by '0' or '1' + */ + static std::vector split(const std::string& reference_string) + { + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) + { + JSON_THROW(detail::parse_error::create(107, 1, + "JSON pointer must be empty or begin with '/' - was: '" + + reference_string + "'")); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + std::size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == 0 (if slash == std::string::npos) + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = (slash == std::string::npos) ? 0 : slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (std::size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + JSON_ASSERT(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || + (reference_token[pos + 1] != '0' && + reference_token[pos + 1] != '1'))) + { + JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); + } + } + + // finally, store the reference token + unescape(reference_token); + result.push_back(reference_token); + } + + return result; + } + + /*! + @brief replace all occurrences of a substring by another string + + @param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t + @param[in] f the substring to replace with @a t + @param[in] t the string to replace @a f + + @pre The search string @a f must not be empty. **This precondition is + enforced with an assertion.** + + @since version 2.0.0 + */ + static void replace_substring(std::string& s, const std::string& f, + const std::string& t) + { + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} + } + + /// escape "~" to "~0" and "/" to "~1" + static std::string escape(std::string s) + { + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; + } + + /// unescape "~1" to tilde and "~0" to slash (order is important!) + static void unescape(std::string& s) + { + replace_substring(s, "~1", "/"); + replace_substring(s, "~0", "~"); + } + + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const BasicJsonType& value, + BasicJsonType& result) + { + switch (value.type()) + { + case detail::value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case detail::value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + escape(element.first), element.second, result); + } + } + break; + } + + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } + } + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + + @throw parse_error.109 if array index is not a number + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + @throw type_error.313 if value cannot be unflattened + */ + static BasicJsonType + unflatten(const BasicJsonType& value) + { + if (JSON_HEDLEY_UNLIKELY(!value.is_object())) + { + JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); + } + + BasicJsonType result; + + // iterate the JSON object values + for (const auto& element : *value.m_value.object) + { + if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) + { + JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); + } + + // assign value to reference pointed to by JSON pointer; Note that if + // the JSON pointer is "" (i.e., points to the whole value), function + // get_and_create returns a reference to result itself. An assignment + // will then create a primitive value. + json_pointer(element.first).get_and_create(result) = element.second; + } + + return result; + } + + /*! + @brief compares two JSON pointers for equality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is equal to @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + /*! + @brief compares two JSON pointers for inequality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is not equal @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens; +}; +} // namespace nlohmann + +// #include + + +#include +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +class json_ref +{ + public: + using value_type = BasicJsonType; + + json_ref(value_type&& value) + : owned_value(std::move(value)) + , value_ref(&owned_value) + , is_rvalue(true) + {} + + json_ref(const value_type& value) + : value_ref(const_cast(&value)) + , is_rvalue(false) + {} + + json_ref(std::initializer_list init) + : owned_value(init) + , value_ref(&owned_value) + , is_rvalue(true) + {} + + template < + class... Args, + enable_if_t::value, int> = 0 > + json_ref(Args && ... args) + : owned_value(std::forward(args)...) + , value_ref(&owned_value) + , is_rvalue(true) + {} + + // class should be movable only + json_ref(json_ref&&) = default; + json_ref(const json_ref&) = delete; + json_ref& operator=(const json_ref&) = delete; + json_ref& operator=(json_ref&&) = delete; + ~json_ref() = default; + + value_type moved_or_copied() const + { + if (is_rvalue) + { + return std::move(*value_ref); + } + return *value_ref; + } + + value_type const& operator*() const + { + return *static_cast(value_ref); + } + + value_type const* operator->() const + { + return static_cast(value_ref); + } + + private: + mutable value_type owned_value = nullptr; + value_type* value_ref = nullptr; + const bool is_rvalue = true; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + + +#include // reverse +#include // array +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // memcpy +#include // numeric_limits +#include // string +#include // isnan, isinf + +// #include + +// #include + +// #include + + +#include // copy +#include // size_t +#include // streamsize +#include // back_inserter +#include // shared_ptr, make_shared +#include // basic_ostream +#include // basic_string +#include // vector +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// abstract output adapter interface +template struct output_adapter_protocol +{ + virtual void write_character(CharType c) = 0; + virtual void write_characters(const CharType* s, std::size_t length) = 0; + virtual ~output_adapter_protocol() = default; +}; + +/// a type to simplify interfaces +template +using output_adapter_t = std::shared_ptr>; + +/// output adapter for byte vectors +template +class output_vector_adapter : public output_adapter_protocol +{ + public: + explicit output_vector_adapter(std::vector& vec) noexcept + : v(vec) + {} + + void write_character(CharType c) override + { + v.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + std::copy(s, s + length, std::back_inserter(v)); + } + + private: + std::vector& v; +}; + +/// output adapter for output streams +template +class output_stream_adapter : public output_adapter_protocol +{ + public: + explicit output_stream_adapter(std::basic_ostream& s) noexcept + : stream(s) + {} + + void write_character(CharType c) override + { + stream.put(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + stream.write(s, static_cast(length)); + } + + private: + std::basic_ostream& stream; +}; + +/// output adapter for basic_string +template> +class output_string_adapter : public output_adapter_protocol +{ + public: + explicit output_string_adapter(StringType& s) noexcept + : str(s) + {} + + void write_character(CharType c) override + { + str.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + str.append(s, length); + } + + private: + StringType& str; +}; + +template> +class output_adapter +{ + public: + output_adapter(std::vector& vec) + : oa(std::make_shared>(vec)) {} + + output_adapter(std::basic_ostream& s) + : oa(std::make_shared>(s)) {} + + output_adapter(StringType& s) + : oa(std::make_shared>(s)) {} + + operator output_adapter_t() + { + return oa; + } + + private: + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// binary writer // +/////////////////// + +/*! +@brief serialization to CBOR and MessagePack values +*/ +template +class binary_writer +{ + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using number_float_t = typename BasicJsonType::number_float_t; + + public: + /*! + @brief create a binary writer + + @param[in] adapter output adapter to write to + */ + explicit binary_writer(output_adapter_t adapter) : oa(adapter) + { + JSON_ASSERT(oa); + } + + /*! + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + void write_bson(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + { + write_bson_object(*j.m_value.object); + break; + } + + default: + { + JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()))); + } + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_cbor(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: + { + oa->write_character(to_char_type(0xF6)); + break; + } + + case value_t::boolean: + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xF5) + : to_char_type(0xF4)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_integer)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + write_number(static_cast(0x20 + positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x38)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x39)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x3A)); + write_number(static_cast(positive_number)); + } + else + { + oa->write_character(to_char_type(0x3B)); + write_number(static_cast(positive_number)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_unsigned)); + } + break; + } + + case value_t::number_float: + { + if (std::isnan(j.m_value.number_float)) + { + // NaN is 0xf97e00 in CBOR + oa->write_character(to_char_type(0xF9)); + oa->write_character(to_char_type(0x7E)); + oa->write_character(to_char_type(0x00)); + } + else if (std::isinf(j.m_value.number_float)) + { + // Infinity is 0xf97c00, -Infinity is 0xf9fc00 + oa->write_character(to_char_type(0xf9)); + oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); + oa->write_character(to_char_type(0x00)); + } + else + { + write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); + } + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 0x17) + { + write_number(static_cast(0x60 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x78)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x79)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + write_number(static_cast(0x80 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x98)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x99)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_cbor(el); + } + break; + } + + case value_t::binary: + { + if (j.m_value.binary->has_subtype()) + { + write_number(static_cast(0xd8)); + write_number(j.m_value.binary->subtype()); + } + + // step 1: write control byte and the binary array size + const auto N = j.m_value.binary->size(); + if (N <= 0x17) + { + write_number(static_cast(0x40 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x58)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x59)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + write_number(static_cast(0xA0 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB8)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBA)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBB)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_cbor(el.first); + write_cbor(el.second); + } + break; + } + + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_msgpack(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: // nil + { + oa->write_character(to_char_type(0xC0)); + break; + } + + case value_t::boolean: // true and false + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xC3) + : to_char_type(0xC2)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we used + // the code from the value_t::number_unsigned case here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 8 + oa->write_character(to_char_type(0xD0)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 16 + oa->write_character(to_char_type(0xD1)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 32 + oa->write_character(to_char_type(0xD2)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 64 + oa->write_character(to_char_type(0xD3)); + write_number(static_cast(j.m_value.number_integer)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + break; + } + + case value_t::number_float: + { + write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 31) + { + // fixstr + write_number(static_cast(0xA0 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 8 + oa->write_character(to_char_type(0xD9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 16 + oa->write_character(to_char_type(0xDA)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 32 + oa->write_character(to_char_type(0xDB)); + write_number(static_cast(N)); + } + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + write_number(static_cast(0x90 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 16 + oa->write_character(to_char_type(0xDC)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 32 + oa->write_character(to_char_type(0xDD)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_msgpack(el); + } + break; + } + + case value_t::binary: + { + // step 0: determine if the binary type has a set subtype to + // determine whether or not to use the ext or fixext types + const bool use_ext = j.m_value.binary->has_subtype(); + + // step 1: write control byte and the byte string length + const auto N = j.m_value.binary->size(); + if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type{}; + bool fixed = true; + if (use_ext) + { + switch (N) + { + case 1: + output_type = 0xD4; // fixext 1 + break; + case 2: + output_type = 0xD5; // fixext 2 + break; + case 4: + output_type = 0xD6; // fixext 4 + break; + case 8: + output_type = 0xD7; // fixext 8 + break; + case 16: + output_type = 0xD8; // fixext 16 + break; + default: + output_type = 0xC7; // ext 8 + fixed = false; + break; + } + + } + else + { + output_type = 0xC4; // bin 8 + fixed = false; + } + + oa->write_character(to_char_type(output_type)); + if (!fixed) + { + write_number(static_cast(N)); + } + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC8 // ext 16 + : 0xC5; // bin 16 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC9 // ext 32 + : 0xC6; // bin 32 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + + // step 1.5: if this is an ext type, write the subtype + if (use_ext) + { + write_number(static_cast(j.m_value.binary->subtype())); + } + + // step 2: write the byte string + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + write_number(static_cast(0x80 | (N & 0xF))); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 16 + oa->write_character(to_char_type(0xDE)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 32 + oa->write_character(to_char_type(0xDF)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_msgpack(el.first); + write_msgpack(el.second); + } + break; + } + + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + @param[in] use_count whether to use '#' prefixes (optimized format) + @param[in] use_type whether to use '$' prefixes (optimized format) + @param[in] add_prefix whether prefixes need to be used for this value + */ + void write_ubjson(const BasicJsonType& j, const bool use_count, + const bool use_type, const bool add_prefix = true) + { + switch (j.type()) + { + case value_t::null: + { + if (add_prefix) + { + oa->write_character(to_char_type('Z')); + } + break; + } + + case value_t::boolean: + { + if (add_prefix) + { + oa->write_character(j.m_value.boolean + ? to_char_type('T') + : to_char_type('F')); + } + break; + } + + case value_t::number_integer: + { + write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); + break; + } + + case value_t::number_unsigned: + { + write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); + break; + } + + case value_t::number_float: + { + write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); + break; + } + + case value_t::string: + { + if (add_prefix) + { + oa->write_character(to_char_type('S')); + } + write_number_with_ubjson_prefix(j.m_value.string->size(), true); + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.array->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin() + 1, j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.array->size(), true); + } + + for (const auto& el : *j.m_value.array) + { + write_ubjson(el, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::binary: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + if (use_type && !j.m_value.binary->empty()) + { + JSON_ASSERT(use_count); + oa->write_character(to_char_type('$')); + oa->write_character('U'); + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.binary->size(), true); + } + + if (use_type) + { + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + j.m_value.binary->size()); + } + else + { + for (size_t i = 0; i < j.m_value.binary->size(); ++i) + { + oa->write_character(to_char_type('U')); + oa->write_character(j.m_value.binary->data()[i]); + } + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::object: + { + if (add_prefix) + { + oa->write_character(to_char_type('{')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.object->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin(), j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.object->size(), true); + } + + for (const auto& el : *j.m_value.object) + { + write_number_with_ubjson_prefix(el.first.size(), true); + oa->write_characters( + reinterpret_cast(el.first.c_str()), + el.first.size()); + write_ubjson(el.second, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type('}')); + } + + break; + } + + default: + break; + } + } + + private: + ////////// + // BSON // + ////////// + + /*! + @return The size of a BSON document entry header, including the id marker + and the entry name size (and its null-terminator). + */ + static std::size_t calc_bson_entry_header_size(const string_t& name) + { + const auto it = name.find(static_cast(0)); + if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) + { + JSON_THROW(out_of_range::create(409, + "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")")); + } + + return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; + } + + /*! + @brief Writes the given @a element_type and @a name to the output adapter + */ + void write_bson_entry_header(const string_t& name, + const std::uint8_t element_type) + { + oa->write_character(to_char_type(element_type)); // boolean + oa->write_characters( + reinterpret_cast(name.c_str()), + name.size() + 1u); + } + + /*! + @brief Writes a BSON element with key @a name and boolean value @a value + */ + void write_bson_boolean(const string_t& name, + const bool value) + { + write_bson_entry_header(name, 0x08); + oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and double value @a value + */ + void write_bson_double(const string_t& name, + const double value) + { + write_bson_entry_header(name, 0x01); + write_number(value); + } + + /*! + @return The size of the BSON-encoded string in @a value + */ + static std::size_t calc_bson_string_size(const string_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and string value @a value + */ + void write_bson_string(const string_t& name, + const string_t& value) + { + write_bson_entry_header(name, 0x02); + + write_number(static_cast(value.size() + 1ul)); + oa->write_characters( + reinterpret_cast(value.c_str()), + value.size() + 1); + } + + /*! + @brief Writes a BSON element with key @a name and null value + */ + void write_bson_null(const string_t& name) + { + write_bson_entry_header(name, 0x0A); + } + + /*! + @return The size of the BSON-encoded integer @a value + */ + static std::size_t calc_bson_integer_size(const std::int64_t value) + { + return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and integer @a value + */ + void write_bson_integer(const string_t& name, + const std::int64_t value) + { + if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) + { + write_bson_entry_header(name, 0x10); // int32 + write_number(static_cast(value)); + } + else + { + write_bson_entry_header(name, 0x12); // int64 + write_number(static_cast(value)); + } + } + + /*! + @return The size of the BSON-encoded unsigned integer in @a j + */ + static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept + { + return (value <= static_cast((std::numeric_limits::max)())) + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and unsigned @a value + */ + void write_bson_unsigned(const string_t& name, + const std::uint64_t value) + { + if (value <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x10 /* int32 */); + write_number(static_cast(value)); + } + else if (value <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x12 /* int64 */); + write_number(static_cast(value)); + } + else + { + JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64")); + } + } + + /*! + @brief Writes a BSON element with key @a name and object @a value + */ + void write_bson_object_entry(const string_t& name, + const typename BasicJsonType::object_t& value) + { + write_bson_entry_header(name, 0x03); // object + write_bson_object(value); + } + + /*! + @return The size of the BSON-encoded array @a value + */ + static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) + { + std::size_t array_index = 0ul; + + const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), std::size_t(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) + { + return result + calc_bson_element_size(std::to_string(array_index++), el); + }); + + return sizeof(std::int32_t) + embedded_document_size + 1ul; + } + + /*! + @return The size of the BSON-encoded binary array @a value + */ + static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and array @a value + */ + void write_bson_array(const string_t& name, + const typename BasicJsonType::array_t& value) + { + write_bson_entry_header(name, 0x04); // array + write_number(static_cast(calc_bson_array_size(value))); + + std::size_t array_index = 0ul; + + for (const auto& el : value) + { + write_bson_element(std::to_string(array_index++), el); + } + + oa->write_character(to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and binary value @a value + */ + void write_bson_binary(const string_t& name, + const binary_t& value) + { + write_bson_entry_header(name, 0x05); + + write_number(static_cast(value.size())); + write_number(value.has_subtype() ? value.subtype() : std::uint8_t(0x00)); + + oa->write_characters(reinterpret_cast(value.data()), value.size()); + } + + /*! + @brief Calculates the size necessary to serialize the JSON value @a j with its @a name + @return The calculated size for the BSON document entry for @a j with the given @a name. + */ + static std::size_t calc_bson_element_size(const string_t& name, + const BasicJsonType& j) + { + const auto header_size = calc_bson_entry_header_size(name); + switch (j.type()) + { + case value_t::object: + return header_size + calc_bson_object_size(*j.m_value.object); + + case value_t::array: + return header_size + calc_bson_array_size(*j.m_value.array); + + case value_t::binary: + return header_size + calc_bson_binary_size(*j.m_value.binary); + + case value_t::boolean: + return header_size + 1ul; + + case value_t::number_float: + return header_size + 8ul; + + case value_t::number_integer: + return header_size + calc_bson_integer_size(j.m_value.number_integer); + + case value_t::number_unsigned: + return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); + + case value_t::string: + return header_size + calc_bson_string_size(*j.m_value.string); + + case value_t::null: + return header_size + 0ul; + + // LCOV_EXCL_START + default: + JSON_ASSERT(false); + return 0ul; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Serializes the JSON value @a j to BSON and associates it with the + key @a name. + @param name The name to associate with the JSON entity @a j within the + current BSON document + @return The size of the BSON entry + */ + void write_bson_element(const string_t& name, + const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + return write_bson_object_entry(name, *j.m_value.object); + + case value_t::array: + return write_bson_array(name, *j.m_value.array); + + case value_t::binary: + return write_bson_binary(name, *j.m_value.binary); + + case value_t::boolean: + return write_bson_boolean(name, j.m_value.boolean); + + case value_t::number_float: + return write_bson_double(name, j.m_value.number_float); + + case value_t::number_integer: + return write_bson_integer(name, j.m_value.number_integer); + + case value_t::number_unsigned: + return write_bson_unsigned(name, j.m_value.number_unsigned); + + case value_t::string: + return write_bson_string(name, *j.m_value.string); + + case value_t::null: + return write_bson_null(name); + + // LCOV_EXCL_START + default: + JSON_ASSERT(false); + return; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Calculates the size of the BSON serialization of the given + JSON-object @a j. + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) + { + std::size_t document_size = std::accumulate(value.begin(), value.end(), std::size_t(0), + [](size_t result, const typename BasicJsonType::object_t::value_type & el) + { + return result += calc_bson_element_size(el.first, el.second); + }); + + return sizeof(std::int32_t) + document_size + 1ul; + } + + /*! + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + void write_bson_object(const typename BasicJsonType::object_t& value) + { + write_number(static_cast(calc_bson_object_size(value))); + + for (const auto& el : value) + { + write_bson_element(el.first, el.second); + } + + oa->write_character(to_char_type(0x00)); + } + + ////////// + // CBOR // + ////////// + + static constexpr CharType get_cbor_float_prefix(float /*unused*/) + { + return to_char_type(0xFA); // Single-Precision Float + } + + static constexpr CharType get_cbor_float_prefix(double /*unused*/) + { + return to_char_type(0xFB); // Double-Precision Float + } + + ///////////// + // MsgPack // + ///////////// + + static constexpr CharType get_msgpack_float_prefix(float /*unused*/) + { + return to_char_type(0xCA); // float 32 + } + + static constexpr CharType get_msgpack_float_prefix(double /*unused*/) + { + return to_char_type(0xCB); // float 64 + } + + //////////// + // UBJSON // + //////////// + + // UBJSON: write number (floating point) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (add_prefix) + { + oa->write_character(get_ubjson_float_prefix(n)); + } + write_number(n); + } + + // UBJSON: write number (unsigned integer) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + } + + // UBJSON: write number (signed integer) + template < typename NumberType, typename std::enable_if < + std::is_signed::value&& + !std::is_floating_point::value, int >::type = 0 > + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + // LCOV_EXCL_START + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + // LCOV_EXCL_STOP + } + + /*! + @brief determine the type prefix of container values + */ + CharType ubjson_prefix(const BasicJsonType& j) const noexcept + { + switch (j.type()) + { + case value_t::null: + return 'Z'; + + case value_t::boolean: + return j.m_value.boolean ? 'T' : 'F'; + + case value_t::number_integer: + { + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'i'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'U'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'I'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'l'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'i'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'U'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'I'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'l'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_float: + return get_ubjson_float_prefix(j.m_value.number_float); + + case value_t::string: + return 'S'; + + case value_t::array: // fallthrough + case value_t::binary: + return '['; + + case value_t::object: + return '{'; + + default: // discarded values + return 'N'; + } + } + + static constexpr CharType get_ubjson_float_prefix(float /*unused*/) + { + return 'd'; // float 32 + } + + static constexpr CharType get_ubjson_float_prefix(double /*unused*/) + { + return 'D'; // float 64 + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /* + @brief write a number to output input + @param[in] n number of type @a NumberType + @tparam NumberType the type of the number + @tparam OutputIsLittleEndian Set to true if output data is + required to be little endian + + @note This function needs to respect the system's endianess, because bytes + in CBOR, MessagePack, and UBJSON are stored in network order (big + endian) and therefore need reordering on little endian systems. + */ + template + void write_number(const NumberType n) + { + // step 1: write number to array of length NumberType + std::array vec; + std::memcpy(vec.data(), &n, sizeof(NumberType)); + + // step 2: write array to output (with possible reordering) + if (is_little_endian != OutputIsLittleEndian) + { + // reverse byte order prior to conversion if necessary + std::reverse(vec.begin(), vec.end()); + } + + oa->write_characters(vec.data(), sizeof(NumberType)); + } + + void write_compact_float(const number_float_t n, detail::input_format_t format) + { + if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && + static_cast(n) <= static_cast((std::numeric_limits::max)()) && + static_cast(static_cast(n)) == static_cast(n)) + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(static_cast(n)) + : get_msgpack_float_prefix(static_cast(n))); + write_number(static_cast(n)); + } + else + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(n) + : get_msgpack_float_prefix(n)); + write_number(n); + } + } + + public: + // The following to_char_type functions are implement the conversion + // between uint8_t and CharType. In case CharType is not unsigned, + // such a conversion is required to allow values greater than 128. + // See for a discussion. + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return *reinterpret_cast(&x); + } + + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > + static CharType to_char_type(std::uint8_t x) noexcept + { + static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); + static_assert(std::is_trivial::value, "CharType must be trivial"); + CharType result; + std::memcpy(&result, &x, sizeof(x)); + return result; + } + + template::value>* = nullptr> + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return x; + } + + template < typename InputCharType, typename C = CharType, + enable_if_t < + std::is_signed::value && + std::is_signed::value && + std::is_same::type>::value + > * = nullptr > + static constexpr CharType to_char_type(InputCharType x) noexcept + { + return x; + } + + private: + /// whether we can assume little endianess + const bool is_little_endian = little_endianess(); + + /// the output + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // reverse, remove, fill, find, none_of +#include // array +#include // localeconv, lconv +#include // labs, isfinite, isnan, signbit +#include // size_t, ptrdiff_t +#include // uint8_t +#include // snprintf +#include // numeric_limits +#include // string, char_traits +#include // is_same +#include // move + +// #include + + +#include // array +#include // signbit, isfinite +#include // intN_t, uintN_t +#include // memcpy, memmove +#include // numeric_limits +#include // conditional + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief implements the Grisu2 algorithm for binary to decimal floating-point +conversion. + +This implementation is a slightly modified version of the reference +implementation which may be obtained from +http://florian.loitsch.com/publications (bench.tar.gz). + +The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. + +For a detailed description of the algorithm see: + +[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with + Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming + Language Design and Implementation, PLDI 2010 +[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", + Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language + Design and Implementation, PLDI 1996 +*/ +namespace dtoa_impl +{ + +template +Target reinterpret_bits(const Source source) +{ + static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); + + Target target; + std::memcpy(&target, &source, sizeof(Source)); + return target; +} + +struct diyfp // f * 2^e +{ + static constexpr int kPrecision = 64; // = q + + std::uint64_t f = 0; + int e = 0; + + constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} + + /*! + @brief returns x - y + @pre x.e == y.e and x.f >= y.f + */ + static diyfp sub(const diyfp& x, const diyfp& y) noexcept + { + JSON_ASSERT(x.e == y.e); + JSON_ASSERT(x.f >= y.f); + + return {x.f - y.f, x.e}; + } + + /*! + @brief returns x * y + @note The result is rounded. (Only the upper q bits are returned.) + */ + static diyfp mul(const diyfp& x, const diyfp& y) noexcept + { + static_assert(kPrecision == 64, "internal error"); + + // Computes: + // f = round((x.f * y.f) / 2^q) + // e = x.e + y.e + q + + // Emulate the 64-bit * 64-bit multiplication: + // + // p = u * v + // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) + // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) + // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) + // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) + // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) + // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) + // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) + // + // (Since Q might be larger than 2^32 - 1) + // + // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) + // + // (Q_hi + H does not overflow a 64-bit int) + // + // = p_lo + 2^64 p_hi + + const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; + const std::uint64_t u_hi = x.f >> 32u; + const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; + const std::uint64_t v_hi = y.f >> 32u; + + const std::uint64_t p0 = u_lo * v_lo; + const std::uint64_t p1 = u_lo * v_hi; + const std::uint64_t p2 = u_hi * v_lo; + const std::uint64_t p3 = u_hi * v_hi; + + const std::uint64_t p0_hi = p0 >> 32u; + const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; + const std::uint64_t p1_hi = p1 >> 32u; + const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; + const std::uint64_t p2_hi = p2 >> 32u; + + std::uint64_t Q = p0_hi + p1_lo + p2_lo; + + // The full product might now be computed as + // + // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) + // p_lo = p0_lo + (Q << 32) + // + // But in this particular case here, the full p_lo is not required. + // Effectively we only need to add the highest bit in p_lo to p_hi (and + // Q_hi + 1 does not overflow). + + Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up + + const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); + + return {h, x.e + y.e + 64}; + } + + /*! + @brief normalize x such that the significand is >= 2^(q-1) + @pre x.f != 0 + */ + static diyfp normalize(diyfp x) noexcept + { + JSON_ASSERT(x.f != 0); + + while ((x.f >> 63u) == 0) + { + x.f <<= 1u; + x.e--; + } + + return x; + } + + /*! + @brief normalize x such that the result has the exponent E + @pre e >= x.e and the upper e - x.e bits of x.f must be zero. + */ + static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept + { + const int delta = x.e - target_exponent; + + JSON_ASSERT(delta >= 0); + JSON_ASSERT(((x.f << delta) >> delta) == x.f); + + return {x.f << delta, target_exponent}; + } +}; + +struct boundaries +{ + diyfp w; + diyfp minus; + diyfp plus; +}; + +/*! +Compute the (normalized) diyfp representing the input number 'value' and its +boundaries. + +@pre value must be finite and positive +*/ +template +boundaries compute_boundaries(FloatType value) +{ + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // Convert the IEEE representation into a diyfp. + // + // If v is denormal: + // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) + // If v is normalized: + // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) + + static_assert(std::numeric_limits::is_iec559, + "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); + + constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) + constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); + constexpr int kMinExp = 1 - kBias; + constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) + + using bits_type = typename std::conditional::type; + + const std::uint64_t bits = reinterpret_bits(value); + const std::uint64_t E = bits >> (kPrecision - 1); + const std::uint64_t F = bits & (kHiddenBit - 1); + + const bool is_denormal = E == 0; + const diyfp v = is_denormal + ? diyfp(F, kMinExp) + : diyfp(F + kHiddenBit, static_cast(E) - kBias); + + // Compute the boundaries m- and m+ of the floating-point value + // v = f * 2^e. + // + // Determine v- and v+, the floating-point predecessor and successor if v, + // respectively. + // + // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) + // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) + // + // v+ = v + 2^e + // + // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ + // between m- and m+ round to v, regardless of how the input rounding + // algorithm breaks ties. + // + // ---+-------------+-------------+-------------+-------------+--- (A) + // v- m- v m+ v+ + // + // -----------------+------+------+-------------+-------------+--- (B) + // v- m- v m+ v+ + + const bool lower_boundary_is_closer = F == 0 && E > 1; + const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); + const diyfp m_minus = lower_boundary_is_closer + ? diyfp(4 * v.f - 1, v.e - 2) // (B) + : diyfp(2 * v.f - 1, v.e - 1); // (A) + + // Determine the normalized w+ = m+. + const diyfp w_plus = diyfp::normalize(m_plus); + + // Determine w- = m- such that e_(w-) = e_(w+). + const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); + + return {diyfp::normalize(v), w_minus, w_plus}; +} + +// Given normalized diyfp w, Grisu needs to find a (normalized) cached +// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies +// within a certain range [alpha, gamma] (Definition 3.2 from [1]) +// +// alpha <= e = e_c + e_w + q <= gamma +// +// or +// +// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q +// <= f_c * f_w * 2^gamma +// +// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies +// +// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma +// +// or +// +// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) +// +// The choice of (alpha,gamma) determines the size of the table and the form of +// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well +// in practice: +// +// The idea is to cut the number c * w = f * 2^e into two parts, which can be +// processed independently: An integral part p1, and a fractional part p2: +// +// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e +// = (f div 2^-e) + (f mod 2^-e) * 2^e +// = p1 + p2 * 2^e +// +// The conversion of p1 into decimal form requires a series of divisions and +// modulos by (a power of) 10. These operations are faster for 32-bit than for +// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be +// achieved by choosing +// +// -e >= 32 or e <= -32 := gamma +// +// In order to convert the fractional part +// +// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... +// +// into decimal form, the fraction is repeatedly multiplied by 10 and the digits +// d[-i] are extracted in order: +// +// (10 * p2) div 2^-e = d[-1] +// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... +// +// The multiplication by 10 must not overflow. It is sufficient to choose +// +// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. +// +// Since p2 = f mod 2^-e < 2^-e, +// +// -e <= 60 or e >= -60 := alpha + +constexpr int kAlpha = -60; +constexpr int kGamma = -32; + +struct cached_power // c = f * 2^e ~= 10^k +{ + std::uint64_t f; + int e; + int k; +}; + +/*! +For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached +power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c +satisfies (Definition 3.2 from [1]) + + alpha <= e_c + e + q <= gamma. +*/ +inline cached_power get_cached_power_for_binary_exponent(int e) +{ + // Now + // + // alpha <= e_c + e + q <= gamma (1) + // ==> f_c * 2^alpha <= c * 2^e * 2^q + // + // and since the c's are normalized, 2^(q-1) <= f_c, + // + // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) + // ==> 2^(alpha - e - 1) <= c + // + // If c were an exact power of ten, i.e. c = 10^k, one may determine k as + // + // k = ceil( log_10( 2^(alpha - e - 1) ) ) + // = ceil( (alpha - e - 1) * log_10(2) ) + // + // From the paper: + // "In theory the result of the procedure could be wrong since c is rounded, + // and the computation itself is approximated [...]. In practice, however, + // this simple function is sufficient." + // + // For IEEE double precision floating-point numbers converted into + // normalized diyfp's w = f * 2^e, with q = 64, + // + // e >= -1022 (min IEEE exponent) + // -52 (p - 1) + // -52 (p - 1, possibly normalize denormal IEEE numbers) + // -11 (normalize the diyfp) + // = -1137 + // + // and + // + // e <= +1023 (max IEEE exponent) + // -52 (p - 1) + // -11 (normalize the diyfp) + // = 960 + // + // This binary exponent range [-1137,960] results in a decimal exponent + // range [-307,324]. One does not need to store a cached power for each + // k in this range. For each such k it suffices to find a cached power + // such that the exponent of the product lies in [alpha,gamma]. + // This implies that the difference of the decimal exponents of adjacent + // table entries must be less than or equal to + // + // floor( (gamma - alpha) * log_10(2) ) = 8. + // + // (A smaller distance gamma-alpha would require a larger table.) + + // NB: + // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. + + constexpr int kCachedPowersMinDecExp = -300; + constexpr int kCachedPowersDecStep = 8; + + static constexpr std::array kCachedPowers = + { + { + { 0xAB70FE17C79AC6CA, -1060, -300 }, + { 0xFF77B1FCBEBCDC4F, -1034, -292 }, + { 0xBE5691EF416BD60C, -1007, -284 }, + { 0x8DD01FAD907FFC3C, -980, -276 }, + { 0xD3515C2831559A83, -954, -268 }, + { 0x9D71AC8FADA6C9B5, -927, -260 }, + { 0xEA9C227723EE8BCB, -901, -252 }, + { 0xAECC49914078536D, -874, -244 }, + { 0x823C12795DB6CE57, -847, -236 }, + { 0xC21094364DFB5637, -821, -228 }, + { 0x9096EA6F3848984F, -794, -220 }, + { 0xD77485CB25823AC7, -768, -212 }, + { 0xA086CFCD97BF97F4, -741, -204 }, + { 0xEF340A98172AACE5, -715, -196 }, + { 0xB23867FB2A35B28E, -688, -188 }, + { 0x84C8D4DFD2C63F3B, -661, -180 }, + { 0xC5DD44271AD3CDBA, -635, -172 }, + { 0x936B9FCEBB25C996, -608, -164 }, + { 0xDBAC6C247D62A584, -582, -156 }, + { 0xA3AB66580D5FDAF6, -555, -148 }, + { 0xF3E2F893DEC3F126, -529, -140 }, + { 0xB5B5ADA8AAFF80B8, -502, -132 }, + { 0x87625F056C7C4A8B, -475, -124 }, + { 0xC9BCFF6034C13053, -449, -116 }, + { 0x964E858C91BA2655, -422, -108 }, + { 0xDFF9772470297EBD, -396, -100 }, + { 0xA6DFBD9FB8E5B88F, -369, -92 }, + { 0xF8A95FCF88747D94, -343, -84 }, + { 0xB94470938FA89BCF, -316, -76 }, + { 0x8A08F0F8BF0F156B, -289, -68 }, + { 0xCDB02555653131B6, -263, -60 }, + { 0x993FE2C6D07B7FAC, -236, -52 }, + { 0xE45C10C42A2B3B06, -210, -44 }, + { 0xAA242499697392D3, -183, -36 }, + { 0xFD87B5F28300CA0E, -157, -28 }, + { 0xBCE5086492111AEB, -130, -20 }, + { 0x8CBCCC096F5088CC, -103, -12 }, + { 0xD1B71758E219652C, -77, -4 }, + { 0x9C40000000000000, -50, 4 }, + { 0xE8D4A51000000000, -24, 12 }, + { 0xAD78EBC5AC620000, 3, 20 }, + { 0x813F3978F8940984, 30, 28 }, + { 0xC097CE7BC90715B3, 56, 36 }, + { 0x8F7E32CE7BEA5C70, 83, 44 }, + { 0xD5D238A4ABE98068, 109, 52 }, + { 0x9F4F2726179A2245, 136, 60 }, + { 0xED63A231D4C4FB27, 162, 68 }, + { 0xB0DE65388CC8ADA8, 189, 76 }, + { 0x83C7088E1AAB65DB, 216, 84 }, + { 0xC45D1DF942711D9A, 242, 92 }, + { 0x924D692CA61BE758, 269, 100 }, + { 0xDA01EE641A708DEA, 295, 108 }, + { 0xA26DA3999AEF774A, 322, 116 }, + { 0xF209787BB47D6B85, 348, 124 }, + { 0xB454E4A179DD1877, 375, 132 }, + { 0x865B86925B9BC5C2, 402, 140 }, + { 0xC83553C5C8965D3D, 428, 148 }, + { 0x952AB45CFA97A0B3, 455, 156 }, + { 0xDE469FBD99A05FE3, 481, 164 }, + { 0xA59BC234DB398C25, 508, 172 }, + { 0xF6C69A72A3989F5C, 534, 180 }, + { 0xB7DCBF5354E9BECE, 561, 188 }, + { 0x88FCF317F22241E2, 588, 196 }, + { 0xCC20CE9BD35C78A5, 614, 204 }, + { 0x98165AF37B2153DF, 641, 212 }, + { 0xE2A0B5DC971F303A, 667, 220 }, + { 0xA8D9D1535CE3B396, 694, 228 }, + { 0xFB9B7CD9A4A7443C, 720, 236 }, + { 0xBB764C4CA7A44410, 747, 244 }, + { 0x8BAB8EEFB6409C1A, 774, 252 }, + { 0xD01FEF10A657842C, 800, 260 }, + { 0x9B10A4E5E9913129, 827, 268 }, + { 0xE7109BFBA19C0C9D, 853, 276 }, + { 0xAC2820D9623BF429, 880, 284 }, + { 0x80444B5E7AA7CF85, 907, 292 }, + { 0xBF21E44003ACDD2D, 933, 300 }, + { 0x8E679C2F5E44FF8F, 960, 308 }, + { 0xD433179D9C8CB841, 986, 316 }, + { 0x9E19DB92B4E31BA9, 1013, 324 }, + } + }; + + // This computation gives exactly the same results for k as + // k = ceil((kAlpha - e - 1) * 0.30102999566398114) + // for |e| <= 1500, but doesn't require floating-point operations. + // NB: log_10(2) ~= 78913 / 2^18 + JSON_ASSERT(e >= -1500); + JSON_ASSERT(e <= 1500); + const int f = kAlpha - e - 1; + const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); + + const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; + JSON_ASSERT(index >= 0); + JSON_ASSERT(static_cast(index) < kCachedPowers.size()); + + const cached_power cached = kCachedPowers[static_cast(index)]; + JSON_ASSERT(kAlpha <= cached.e + e + 64); + JSON_ASSERT(kGamma >= cached.e + e + 64); + + return cached; +} + +/*! +For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. +For n == 0, returns 1 and sets pow10 := 1. +*/ +inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) +{ + // LCOV_EXCL_START + if (n >= 1000000000) + { + pow10 = 1000000000; + return 10; + } + // LCOV_EXCL_STOP + else if (n >= 100000000) + { + pow10 = 100000000; + return 9; + } + else if (n >= 10000000) + { + pow10 = 10000000; + return 8; + } + else if (n >= 1000000) + { + pow10 = 1000000; + return 7; + } + else if (n >= 100000) + { + pow10 = 100000; + return 6; + } + else if (n >= 10000) + { + pow10 = 10000; + return 5; + } + else if (n >= 1000) + { + pow10 = 1000; + return 4; + } + else if (n >= 100) + { + pow10 = 100; + return 3; + } + else if (n >= 10) + { + pow10 = 10; + return 2; + } + else + { + pow10 = 1; + return 1; + } +} + +inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, + std::uint64_t rest, std::uint64_t ten_k) +{ + JSON_ASSERT(len >= 1); + JSON_ASSERT(dist <= delta); + JSON_ASSERT(rest <= delta); + JSON_ASSERT(ten_k > 0); + + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // ten_k + // <------> + // <---- rest ----> + // --------------[------------------+----+--------------]-------------- + // w V + // = buf * 10^k + // + // ten_k represents a unit-in-the-last-place in the decimal representation + // stored in buf. + // Decrement buf by ten_k while this takes buf closer to w. + + // The tests are written in this order to avoid overflow in unsigned + // integer arithmetic. + + while (rest < dist + && delta - rest >= ten_k + && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) + { + JSON_ASSERT(buf[len - 1] != '0'); + buf[len - 1]--; + rest += ten_k; + } +} + +/*! +Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. +M- and M+ must be normalized and share the same exponent -60 <= e <= -32. +*/ +inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, + diyfp M_minus, diyfp w, diyfp M_plus) +{ + static_assert(kAlpha >= -60, "internal error"); + static_assert(kGamma <= -32, "internal error"); + + // Generates the digits (and the exponent) of a decimal floating-point + // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's + // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. + // + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // Grisu2 generates the digits of M+ from left to right and stops as soon as + // V is in [M-,M+]. + + JSON_ASSERT(M_plus.e >= kAlpha); + JSON_ASSERT(M_plus.e <= kGamma); + + std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) + std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) + + // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): + // + // M+ = f * 2^e + // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e + // = ((p1 ) * 2^-e + (p2 )) * 2^e + // = p1 + p2 * 2^e + + const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); + + auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) + std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e + + // 1) + // + // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] + + JSON_ASSERT(p1 > 0); + + std::uint32_t pow10; + const int k = find_largest_pow10(p1, pow10); + + // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) + // + // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) + // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) + // + // M+ = p1 + p2 * 2^e + // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e + // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e + // = d[k-1] * 10^(k-1) + ( rest) * 2^e + // + // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) + // + // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] + // + // but stop as soon as + // + // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e + + int n = k; + while (n > 0) + { + // Invariants: + // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) + // pow10 = 10^(n-1) <= p1 < 10^n + // + const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) + const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) + // + // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e + // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) + // + p1 = r; + n--; + // + // M+ = buffer * 10^n + (p1 + p2 * 2^e) + // pow10 = 10^n + // + + // Now check if enough digits have been generated. + // Compute + // + // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e + // + // Note: + // Since rest and delta share the same exponent e, it suffices to + // compare the significands. + const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; + if (rest <= delta) + { + // V = buffer * 10^n, with M- <= V <= M+. + + decimal_exponent += n; + + // We may now just stop. But instead look if the buffer could be + // decremented to bring V closer to w. + // + // pow10 = 10^n is now 1 ulp in the decimal representation V. + // The rounding procedure works with diyfp's with an implicit + // exponent of e. + // + // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e + // + const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; + grisu2_round(buffer, length, dist, delta, rest, ten_n); + + return; + } + + pow10 /= 10; + // + // pow10 = 10^(n-1) <= p1 < 10^n + // Invariants restored. + } + + // 2) + // + // The digits of the integral part have been generated: + // + // M+ = d[k-1]...d[1]d[0] + p2 * 2^e + // = buffer + p2 * 2^e + // + // Now generate the digits of the fractional part p2 * 2^e. + // + // Note: + // No decimal point is generated: the exponent is adjusted instead. + // + // p2 actually represents the fraction + // + // p2 * 2^e + // = p2 / 2^-e + // = d[-1] / 10^1 + d[-2] / 10^2 + ... + // + // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) + // + // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m + // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) + // + // using + // + // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) + // = ( d) * 2^-e + ( r) + // + // or + // 10^m * p2 * 2^e = d + r * 2^e + // + // i.e. + // + // M+ = buffer + p2 * 2^e + // = buffer + 10^-m * (d + r * 2^e) + // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e + // + // and stop as soon as 10^-m * r * 2^e <= delta * 2^e + + JSON_ASSERT(p2 > delta); + + int m = 0; + for (;;) + { + // Invariant: + // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e + // = buffer * 10^-m + 10^-m * (p2 ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e + // + JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); + p2 *= 10; + const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e + const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e + // + // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) + // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + p2 = r; + m++; + // + // M+ = buffer * 10^-m + 10^-m * p2 * 2^e + // Invariant restored. + + // Check if enough digits have been generated. + // + // 10^-m * p2 * 2^e <= delta * 2^e + // p2 * 2^e <= 10^m * delta * 2^e + // p2 <= 10^m * delta + delta *= 10; + dist *= 10; + if (p2 <= delta) + { + break; + } + } + + // V = buffer * 10^-m, with M- <= V <= M+. + + decimal_exponent -= m; + + // 1 ulp in the decimal representation is now 10^-m. + // Since delta and dist are now scaled by 10^m, we need to do the + // same with ulp in order to keep the units in sync. + // + // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e + // + const std::uint64_t ten_m = one.f; + grisu2_round(buffer, length, dist, delta, p2, ten_m); + + // By construction this algorithm generates the shortest possible decimal + // number (Loitsch, Theorem 6.2) which rounds back to w. + // For an input number of precision p, at least + // + // N = 1 + ceil(p * log_10(2)) + // + // decimal digits are sufficient to identify all binary floating-point + // numbers (Matula, "In-and-Out conversions"). + // This implies that the algorithm does not produce more than N decimal + // digits. + // + // N = 17 for p = 53 (IEEE double precision) + // N = 9 for p = 24 (IEEE single precision) +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +JSON_HEDLEY_NON_NULL(1) +inline void grisu2(char* buf, int& len, int& decimal_exponent, + diyfp m_minus, diyfp v, diyfp m_plus) +{ + JSON_ASSERT(m_plus.e == m_minus.e); + JSON_ASSERT(m_plus.e == v.e); + + // --------(-----------------------+-----------------------)-------- (A) + // m- v m+ + // + // --------------------(-----------+-----------------------)-------- (B) + // m- v m+ + // + // First scale v (and m- and m+) such that the exponent is in the range + // [alpha, gamma]. + + const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); + + const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k + + // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] + const diyfp w = diyfp::mul(v, c_minus_k); + const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); + const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); + + // ----(---+---)---------------(---+---)---------------(---+---)---- + // w- w w+ + // = c*m- = c*v = c*m+ + // + // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and + // w+ are now off by a small amount. + // In fact: + // + // w - v * 10^k < 1 ulp + // + // To account for this inaccuracy, add resp. subtract 1 ulp. + // + // --------+---[---------------(---+---)---------------]---+-------- + // w- M- w M+ w+ + // + // Now any number in [M-, M+] (bounds included) will round to w when input, + // regardless of how the input rounding algorithm breaks ties. + // + // And digit_gen generates the shortest possible such number in [M-, M+]. + // Note that this does not mean that Grisu2 always generates the shortest + // possible number in the interval (m-, m+). + const diyfp M_minus(w_minus.f + 1, w_minus.e); + const diyfp M_plus (w_plus.f - 1, w_plus.e ); + + decimal_exponent = -cached.k; // = -(-k) = k + + grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +template +JSON_HEDLEY_NON_NULL(1) +void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) +{ + static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, + "internal error: not enough precision"); + + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // If the neighbors (and boundaries) of 'value' are always computed for double-precision + // numbers, all float's can be recovered using strtod (and strtof). However, the resulting + // decimal representations are not exactly "short". + // + // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) + // says "value is converted to a string as if by std::sprintf in the default ("C") locale" + // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' + // does. + // On the other hand, the documentation for 'std::to_chars' requires that "parsing the + // representation using the corresponding std::from_chars function recovers value exactly". That + // indicates that single precision floating-point numbers should be recovered using + // 'std::strtof'. + // + // NB: If the neighbors are computed for single-precision numbers, there is a single float + // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision + // value is off by 1 ulp. +#if 0 + const boundaries w = compute_boundaries(static_cast(value)); +#else + const boundaries w = compute_boundaries(value); +#endif + + grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); +} + +/*! +@brief appends a decimal representation of e to buf +@return a pointer to the element following the exponent. +@pre -1000 < e < 1000 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* append_exponent(char* buf, int e) +{ + JSON_ASSERT(e > -1000); + JSON_ASSERT(e < 1000); + + if (e < 0) + { + e = -e; + *buf++ = '-'; + } + else + { + *buf++ = '+'; + } + + auto k = static_cast(e); + if (k < 10) + { + // Always print at least two digits in the exponent. + // This is for compatibility with printf("%g"). + *buf++ = '0'; + *buf++ = static_cast('0' + k); + } + else if (k < 100) + { + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + else + { + *buf++ = static_cast('0' + k / 100); + k %= 100; + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + + return buf; +} + +/*! +@brief prettify v = buf * 10^decimal_exponent + +If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point +notation. Otherwise it will be printed in exponential notation. + +@pre min_exp < 0 +@pre max_exp > 0 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* format_buffer(char* buf, int len, int decimal_exponent, + int min_exp, int max_exp) +{ + JSON_ASSERT(min_exp < 0); + JSON_ASSERT(max_exp > 0); + + const int k = len; + const int n = len + decimal_exponent; + + // v = buf * 10^(n-k) + // k is the length of the buffer (number of decimal digits) + // n is the position of the decimal point relative to the start of the buffer. + + if (k <= n && n <= max_exp) + { + // digits[000] + // len <= max_exp + 2 + + std::memset(buf + k, '0', static_cast(n) - static_cast(k)); + // Make it look like a floating-point number (#362, #378) + buf[n + 0] = '.'; + buf[n + 1] = '0'; + return buf + (static_cast(n) + 2); + } + + if (0 < n && n <= max_exp) + { + // dig.its + // len <= max_digits10 + 1 + + JSON_ASSERT(k > n); + + std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); + buf[n] = '.'; + return buf + (static_cast(k) + 1U); + } + + if (min_exp < n && n <= 0) + { + // 0.[000]digits + // len <= 2 + (-min_exp - 1) + max_digits10 + + std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', static_cast(-n)); + return buf + (2U + static_cast(-n) + static_cast(k)); + } + + if (k == 1) + { + // dE+123 + // len <= 1 + 5 + + buf += 1; + } + else + { + // d.igitsE+123 + // len <= max_digits10 + 1 + 5 + + std::memmove(buf + 2, buf + 1, static_cast(k) - 1); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent(buf, n - 1); +} + +} // namespace dtoa_impl + +/*! +@brief generates a decimal representation of the floating-point number value in [first, last). + +The format of the resulting decimal representation is similar to printf's %g +format. Returns an iterator pointing past-the-end of the decimal representation. + +@note The input number must be finite, i.e. NaN's and Inf's are not supported. +@note The buffer must be large enough. +@note The result is NOT null-terminated. +*/ +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* to_chars(char* first, const char* last, FloatType value) +{ + static_cast(last); // maybe unused - fix warning + JSON_ASSERT(std::isfinite(value)); + + // Use signbit(value) instead of (value < 0) since signbit works for -0. + if (std::signbit(value)) + { + value = -value; + *first++ = '-'; + } + + if (value == 0) // +-0 + { + *first++ = '0'; + // Make it look like a floating-point number (#362, #378) + *first++ = '.'; + *first++ = '0'; + return first; + } + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); + + // Compute v = buffer * 10^decimal_exponent. + // The decimal digits are stored in the buffer, which needs to be interpreted + // as an unsigned decimal integer. + // len is the length of the buffer, i.e. the number of decimal digits. + int len = 0; + int decimal_exponent = 0; + dtoa_impl::grisu2(first, len, decimal_exponent, value); + + JSON_ASSERT(len <= std::numeric_limits::max_digits10); + + // Format the buffer like printf("%.*g", prec, value) + constexpr int kMinExp = -4; + // Use digits10 here to increase compatibility with version 2. + constexpr int kMaxExp = std::numeric_limits::digits10; + + JSON_ASSERT(last - first >= kMaxExp + 2); + JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + + return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); +} + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// serialization // +/////////////////// + +/// how to treat decoding errors +enum class error_handler_t +{ + strict, ///< throw a type_error exception in case of invalid UTF-8 + replace, ///< replace invalid UTF-8 sequences with U+FFFD + ignore ///< ignore invalid UTF-8 sequences +}; + +template +class serializer +{ + using string_t = typename BasicJsonType::string_t; + using number_float_t = typename BasicJsonType::number_float_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using binary_char_t = typename BasicJsonType::binary_t::value_type; + static constexpr std::uint8_t UTF8_ACCEPT = 0; + static constexpr std::uint8_t UTF8_REJECT = 1; + + public: + /*! + @param[in] s output stream to serialize to + @param[in] ichar indentation character to use + @param[in] error_handler_ how to react on decoding errors + */ + serializer(output_adapter_t s, const char ichar, + error_handler_t error_handler_ = error_handler_t::strict) + : o(std::move(s)) + , loc(std::localeconv()) + , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) + , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) + , indent_char(ichar) + , indent_string(512, indent_char) + , error_handler(error_handler_) + {} + + // delete because of pointer members + serializer(const serializer&) = delete; + serializer& operator=(const serializer&) = delete; + serializer(serializer&&) = delete; + serializer& operator=(serializer&&) = delete; + ~serializer() = default; + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and organizes + the serialization internally. The indentation level is propagated as + additional parameter. In case of arrays and objects, the function is + called recursively. + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + - binary values are serialized as objects containing the subtype and the + byte array + + @param[in] val value to serialize + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(const BasicJsonType& val, + const bool pretty_print, + const bool ensure_ascii, + const unsigned int indent_step, + const unsigned int current_indent = 0) + { + switch (val.m_type) + { + case value_t::object: + { + if (val.m_value.object->empty()) + { + o->write_characters("{}", 2); + return; + } + + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_character('{'); + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + + o->write_character('}'); + } + + return; + } + + case value_t::array: + { + if (val.m_value.array->empty()) + { + o->write_characters("[]", 2); + return; + } + + if (pretty_print) + { + o->write_characters("[\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + dump(*i, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + o->write_characters(indent_string.c_str(), new_indent); + dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character(']'); + } + else + { + o->write_character('['); + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + dump(*i, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); + + o->write_character(']'); + } + + return; + } + + case value_t::string: + { + o->write_character('\"'); + dump_escaped(*val.m_value.string, ensure_ascii); + o->write_character('\"'); + return; + } + + case value_t::binary: + { + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"bytes\": [", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_characters(", ", 2); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\n", 3); + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"subtype\": ", 11); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + } + else + { + o->write_characters("null", 4); + } + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_characters("{\"bytes\":[", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_character(','); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\"subtype\":", 12); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + o->write_character('}'); + } + else + { + o->write_characters("null}", 5); + } + } + return; + } + + case value_t::boolean: + { + if (val.m_value.boolean) + { + o->write_characters("true", 4); + } + else + { + o->write_characters("false", 5); + } + return; + } + + case value_t::number_integer: + { + dump_integer(val.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float(val.m_value.number_float); + return; + } + + case value_t::discarded: + { + o->write_characters("", 11); + return; + } + + case value_t::null: + { + o->write_characters("null", 4); + return; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + } + + private: + /*! + @brief dump escaped string + + Escape a string by replacing certain special characters by a sequence of an + escape character (backslash) and another character and other control + characters by a sequence of "\u" followed by a four-digit hex + representation. The escaped string is written to output stream @a o. + + @param[in] s the string to escape + @param[in] ensure_ascii whether to escape non-ASCII characters with + \uXXXX sequences + + @complexity Linear in the length of string @a s. + */ + void dump_escaped(const string_t& s, const bool ensure_ascii) + { + std::uint32_t codepoint; + std::uint8_t state = UTF8_ACCEPT; + std::size_t bytes = 0; // number of bytes written to string_buffer + + // number of bytes written at the point of the last valid byte + std::size_t bytes_after_last_accept = 0; + std::size_t undumped_chars = 0; + + for (std::size_t i = 0; i < s.size(); ++i) + { + const auto byte = static_cast(s[i]); + + switch (decode(state, codepoint, byte)) + { + case UTF8_ACCEPT: // decode found a new code point + { + switch (codepoint) + { + case 0x08: // backspace + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'b'; + break; + } + + case 0x09: // horizontal tab + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 't'; + break; + } + + case 0x0A: // newline + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'n'; + break; + } + + case 0x0C: // formfeed + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'f'; + break; + } + + case 0x0D: // carriage return + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'r'; + break; + } + + case 0x22: // quotation mark + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\"'; + break; + } + + case 0x5C: // reverse solidus + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\\'; + break; + } + + default: + { + // escape control characters (0x00..0x1F) or, if + // ensure_ascii parameter is used, non-ASCII characters + if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) + { + if (codepoint <= 0xFFFF) + { + (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", + static_cast(codepoint)); + bytes += 6; + } + else + { + (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", + static_cast(0xD7C0u + (codepoint >> 10u)), + static_cast(0xDC00u + (codepoint & 0x3FFu))); + bytes += 12; + } + } + else + { + // copy byte to buffer (all previous bytes + // been copied have in default case above) + string_buffer[bytes++] = s[i]; + } + break; + } + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + // remember the byte position of this accept + bytes_after_last_accept = bytes; + undumped_chars = 0; + break; + } + + case UTF8_REJECT: // decode found invalid UTF-8 byte + { + switch (error_handler) + { + case error_handler_t::strict: + { + std::string sn(3, '\0'); + (std::snprintf)(&sn[0], sn.size(), "%.2X", byte); + JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn)); + } + + case error_handler_t::ignore: + case error_handler_t::replace: + { + // in case we saw this character the first time, we + // would like to read it again, because the byte + // may be OK for itself, but just not OK for the + // previous sequence + if (undumped_chars > 0) + { + --i; + } + + // reset length buffer to the last accepted index; + // thus removing/ignoring the invalid characters + bytes = bytes_after_last_accept; + + if (error_handler == error_handler_t::replace) + { + // add a replacement character + if (ensure_ascii) + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'u'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'd'; + } + else + { + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + bytes_after_last_accept = bytes; + } + + undumped_chars = 0; + + // continue processing the string + state = UTF8_ACCEPT; + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + break; + } + + default: // decode found yet incomplete multi-byte code point + { + if (!ensure_ascii) + { + // code point will not be escaped - copy byte to buffer + string_buffer[bytes++] = s[i]; + } + ++undumped_chars; + break; + } + } + } + + // we finished processing the string + if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) + { + // write buffer + if (bytes > 0) + { + o->write_characters(string_buffer.data(), bytes); + } + } + else + { + // we finish reading, but do not accept: string was incomplete + switch (error_handler) + { + case error_handler_t::strict: + { + std::string sn(3, '\0'); + (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast(s.back())); + JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn)); + } + + case error_handler_t::ignore: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + break; + } + + case error_handler_t::replace: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + // add a replacement character + if (ensure_ascii) + { + o->write_characters("\\ufffd", 6); + } + else + { + o->write_characters("\xEF\xBF\xBD", 3); + } + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + } + } + + /*! + @brief count digits + + Count the number of decimal (base 10) digits for an input unsigned integer. + + @param[in] x unsigned integer number to count its digits + @return number of decimal digits + */ + inline unsigned int count_digits(number_unsigned_t x) noexcept + { + unsigned int n_digits = 1; + for (;;) + { + if (x < 10) + { + return n_digits; + } + if (x < 100) + { + return n_digits + 1; + } + if (x < 1000) + { + return n_digits + 2; + } + if (x < 10000) + { + return n_digits + 3; + } + x = x / 10000u; + n_digits += 4; + } + } + + /*! + @brief dump an integer + + Dump a given integer to output stream @a o. Works internally with + @a number_buffer. + + @param[in] x integer number (signed or unsigned) to dump + @tparam NumberType either @a number_integer_t or @a number_unsigned_t + */ + template < typename NumberType, detail::enable_if_t < + std::is_same::value || + std::is_same::value || + std::is_same::value, + int > = 0 > + void dump_integer(NumberType x) + { + static constexpr std::array, 100> digits_to_99 + { + { + {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, + {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, + {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, + {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, + {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, + {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, + {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, + {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, + {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, + {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, + } + }; + + // special case for "0" + if (x == 0) + { + o->write_character('0'); + return; + } + + // use a pointer to fill the buffer + auto buffer_ptr = number_buffer.begin(); + + const bool is_negative = std::is_same::value && !(x >= 0); // see issue #755 + number_unsigned_t abs_value; + + unsigned int n_chars; + + if (is_negative) + { + *buffer_ptr = '-'; + abs_value = remove_sign(static_cast(x)); + + // account one more byte for the minus sign + n_chars = 1 + count_digits(abs_value); + } + else + { + abs_value = static_cast(x); + n_chars = count_digits(abs_value); + } + + // spare 1 byte for '\0' + JSON_ASSERT(n_chars < number_buffer.size() - 1); + + // jump to the end to generate the string from backward + // so we later avoid reversing the result + buffer_ptr += n_chars; + + // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu + // See: https://www.youtube.com/watch?v=o4-CwDo2zpg + while (abs_value >= 100) + { + const auto digits_index = static_cast((abs_value % 100)); + abs_value /= 100; + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + + if (abs_value >= 10) + { + const auto digits_index = static_cast(abs_value); + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + else + { + *(--buffer_ptr) = static_cast('0' + abs_value); + } + + o->write_characters(number_buffer.data(), n_chars); + } + + /*! + @brief dump a floating-point number + + Dump a given floating-point number to output stream @a o. Works internally + with @a number_buffer. + + @param[in] x floating-point number to dump + */ + void dump_float(number_float_t x) + { + // NaN / inf + if (!std::isfinite(x)) + { + o->write_characters("null", 4); + return; + } + + // If number_float_t is an IEEE-754 single or double precision number, + // use the Grisu2 algorithm to produce short numbers which are + // guaranteed to round-trip, using strtof and strtod, resp. + // + // NB: The test below works if == . + static constexpr bool is_ieee_single_or_double + = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || + (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); + + dump_float(x, std::integral_constant()); + } + + void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) + { + char* begin = number_buffer.data(); + char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); + + o->write_characters(begin, static_cast(end - begin)); + } + + void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) + { + // get number of digits for a float -> text -> float round-trip + static constexpr auto d = std::numeric_limits::max_digits10; + + // the actual conversion + std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + + // negative value indicates an error + JSON_ASSERT(len > 0); + // check if buffer was large enough + JSON_ASSERT(static_cast(len) < number_buffer.size()); + + // erase thousands separator + if (thousands_sep != '\0') + { + const auto end = std::remove(number_buffer.begin(), + number_buffer.begin() + len, thousands_sep); + std::fill(end, number_buffer.end(), '\0'); + JSON_ASSERT((end - number_buffer.begin()) <= len); + len = (end - number_buffer.begin()); + } + + // convert decimal point to '.' + if (decimal_point != '\0' && decimal_point != '.') + { + const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); + if (dec_pos != number_buffer.end()) + { + *dec_pos = '.'; + } + } + + o->write_characters(number_buffer.data(), static_cast(len)); + + // determine if need to append ".0" + const bool value_is_int_like = + std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, + [](char c) + { + return c == '.' || c == 'e'; + }); + + if (value_is_int_like) + { + o->write_characters(".0", 2); + } + } + + /*! + @brief check whether a string is UTF-8 encoded + + The function checks each byte of a string whether it is UTF-8 encoded. The + result of the check is stored in the @a state parameter. The function must + be called initially with state 0 (accept). State 1 means the string must + be rejected, because the current byte is not allowed. If the string is + completely processed, but the state is non-zero, the string ended + prematurely; that is, the last byte indicated more bytes should have + followed. + + @param[in,out] state the state of the decoding + @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) + @param[in] byte next byte to decode + @return new state + + @note The function has been edited: a std::array is used. + + @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann + @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + */ + static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept + { + static const std::array utf8d = + { + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF + 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF + 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 + } + }; + + const std::uint8_t type = utf8d[byte]; + + codep = (state != UTF8_ACCEPT) + ? (byte & 0x3fu) | (codep << 6u) + : (0xFFu >> type) & (byte); + + std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); + JSON_ASSERT(index < 400); + state = utf8d[index]; + return state; + } + + /* + * Overload to make the compiler happy while it is instantiating + * dump_integer for number_unsigned_t. + * Must never be called. + */ + number_unsigned_t remove_sign(number_unsigned_t x) + { + JSON_ASSERT(false); // LCOV_EXCL_LINE + return x; // LCOV_EXCL_LINE + } + + /* + * Helper function for dump_integer + * + * This function takes a negative signed integer and returns its absolute + * value as unsigned integer. The plus/minus shuffling is necessary as we can + * not directly remove the sign of an arbitrary signed integer as the + * absolute values of INT_MIN and INT_MAX are usually not the same. See + * #1708 for details. + */ + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); + return static_cast(-(x + 1)) + 1; + } + + private: + /// the output of the serializer + output_adapter_t o = nullptr; + + /// a (hopefully) large enough character buffer + std::array number_buffer{{}}; + + /// the locale + const std::lconv* loc = nullptr; + /// the locale's thousand separator character + const char thousands_sep = '\0'; + /// the locale's decimal point character + const char decimal_point = '\0'; + + /// string buffer + std::array string_buffer{{}}; + + /// the indentation character + const char indent_char; + /// the indentation string + string_t indent_string; + + /// error_handler how to react on decoding errors + const error_handler_t error_handler; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // less +#include // allocator +#include // pair +#include // vector + +namespace nlohmann +{ + +/// ordered_map: a minimal map-like container that preserves insertion order +/// for use within nlohmann::basic_json +template , + class Allocator = std::allocator>> + struct ordered_map : std::vector, Allocator> +{ + using key_type = Key; + using mapped_type = T; + using Container = std::vector, Allocator>; + using typename Container::iterator; + using typename Container::const_iterator; + using typename Container::size_type; + using typename Container::value_type; + + // Explicit constructors instead of `using Container::Container` + // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) + ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} + template + ordered_map(It first, It last, const Allocator& alloc = Allocator()) + : Container{first, last, alloc} {} + ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) + : Container{init, alloc} {} + + std::pair emplace(const key_type& key, T&& t) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return {it, false}; + } + } + Container::emplace_back(key, t); + return {--this->end(), true}; + } + + T& operator[](const Key& key) + { + return emplace(key, T{}).first->second; + } + + const T& operator[](const Key& key) const + { + return at(key); + } + + T& at(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + throw std::out_of_range("key not found"); + } + + const T& at(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + throw std::out_of_range("key not found"); + } + + size_type erase(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return 1; + } + } + return 0; + } + + iterator erase(iterator pos) + { + auto it = pos; + + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return pos; + } + + size_type count(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return 1; + } + } + return 0; + } + + iterator find(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + const_iterator find(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + std::pair insert( value_type&& value ) + { + return emplace(value.first, std::move(value.second)); + } + + std::pair insert( const value_type& value ) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == value.first) + { + return {it, false}; + } + } + Container::push_back(value); + return {--this->end(), true}; + } +}; + +} // namespace nlohmann + + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ + +/*! +@brief a class to store JSON values + +@tparam ObjectType type for JSON objects (`std::map` by default; will be used +in @ref object_t) +@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used +in @ref array_t) +@tparam StringType type for JSON strings and object keys (`std::string` by +default; will be used in @ref string_t) +@tparam BooleanType type for JSON booleans (`bool` by default; will be used +in @ref boolean_t) +@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by +default; will be used in @ref number_integer_t) +@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c +`uint64_t` by default; will be used in @ref number_unsigned_t) +@tparam NumberFloatType type for JSON floating-point numbers (`double` by +default; will be used in @ref number_float_t) +@tparam BinaryType type for packed binary data for compatibility with binary +serialization formats (`std::vector` by default; will be used in +@ref binary_t) +@tparam AllocatorType type of the allocator to use (`std::allocator` by +default) +@tparam JSONSerializer the serializer to resolve internal calls to `to_json()` +and `from_json()` (@ref adl_serializer by default) + +@requirement The class satisfies the following concept requirements: +- Basic + - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): + JSON values can be default constructed. The result will be a JSON null + value. + - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): + A JSON value can be constructed from an rvalue argument. + - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): + A JSON value can be copy-constructed from an lvalue expression. + - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): + A JSON value van be assigned from an rvalue argument. + - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): + A JSON value can be copy-assigned from an lvalue expression. + - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): + JSON values can be destructed. +- Layout + - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): + JSON values have + [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): + All non-static data members are private and standard layout types, the + class has no virtual functions or (virtual) base classes. +- Library-wide + - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): + JSON values can be compared with `==`, see @ref + operator==(const_reference,const_reference). + - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): + JSON values can be compared with `<`, see @ref + operator<(const_reference,const_reference). + - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): + Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of + other compatible types, using unqualified function call @ref swap(). + - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): + JSON values can be compared against `std::nullptr_t` objects which are used + to model the `null` value. +- Container + - [Container](https://en.cppreference.com/w/cpp/named_req/Container): + JSON values can be used like STL containers and provide iterator access. + - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); + JSON values can be used like STL containers and provide reverse iterator + access. + +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@internal +@note ObjectType trick from https://stackoverflow.com/a/9860911 +@endinternal + +@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange +Format](http://rfc7159.net/rfc7159) + +@since version 1.0.0 + +@nosubgrouping +*/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +class basic_json +{ + private: + template friend struct detail::external_constructor; + friend ::nlohmann::json_pointer; + + template + friend class ::nlohmann::detail::parser; + friend ::nlohmann::detail::serializer; + template + friend class ::nlohmann::detail::iter_impl; + template + friend class ::nlohmann::detail::binary_writer; + template + friend class ::nlohmann::detail::binary_reader; + template + friend class ::nlohmann::detail::json_sax_dom_parser; + template + friend class ::nlohmann::detail::json_sax_dom_callback_parser; + + /// workaround type for MSVC + using basic_json_t = NLOHMANN_BASIC_JSON_TPL; + + // convenience aliases for types residing in namespace detail; + using lexer = ::nlohmann::detail::lexer_base; + + template + static ::nlohmann::detail::parser parser( + InputAdapterType adapter, + detail::parser_callback_tcb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false + ) + { + return ::nlohmann::detail::parser(std::move(adapter), + std::move(cb), allow_exceptions, ignore_comments); + } + + using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; + template + using internal_iterator = ::nlohmann::detail::internal_iterator; + template + using iter_impl = ::nlohmann::detail::iter_impl; + template + using iteration_proxy = ::nlohmann::detail::iteration_proxy; + template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; + + template + using output_adapter_t = ::nlohmann::detail::output_adapter_t; + + template + using binary_reader = ::nlohmann::detail::binary_reader; + template using binary_writer = ::nlohmann::detail::binary_writer; + + using serializer = ::nlohmann::detail::serializer; + + public: + using value_t = detail::value_t; + /// JSON Pointer, see @ref nlohmann::json_pointer + using json_pointer = ::nlohmann::json_pointer; + template + using json_serializer = JSONSerializer; + /// how to treat decoding errors + using error_handler_t = detail::error_handler_t; + /// how to treat CBOR tags + using cbor_tag_handler_t = detail::cbor_tag_handler_t; + /// helper type for initializer lists of basic_json values + using initializer_list_t = std::initializer_list>; + + using input_format_t = detail::input_format_t; + /// SAX interface type, see @ref nlohmann::json_sax + using json_sax_t = json_sax; + + //////////////// + // exceptions // + //////////////// + + /// @name exceptions + /// Classes to implement user-defined exceptions. + /// @{ + + /// @copydoc detail::exception + using exception = detail::exception; + /// @copydoc detail::parse_error + using parse_error = detail::parse_error; + /// @copydoc detail::invalid_iterator + using invalid_iterator = detail::invalid_iterator; + /// @copydoc detail::type_error + using type_error = detail::type_error; + /// @copydoc detail::out_of_range + using out_of_range = detail::out_of_range; + /// @copydoc detail::other_error + using other_error = detail::other_error; + + /// @} + + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref basic_json like any other STL + /// container. + /// @{ + + /// the type of elements in a basic_json container + using value_type = basic_json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the allocator type + using allocator_type = AllocatorType; + + /// the type of an element pointer + using pointer = typename std::allocator_traits::pointer; + /// the type of an element const pointer + using const_pointer = typename std::allocator_traits::const_pointer; + + /// an iterator for a basic_json container + using iterator = iter_impl; + /// a const iterator for a basic_json container + using const_iterator = iter_impl; + /// a reverse iterator for a basic_json container + using reverse_iterator = json_reverse_iterator; + /// a const reverse iterator for a basic_json container + using const_reverse_iterator = json_reverse_iterator; + + /// @} + + + /*! + @brief returns the allocator associated with the container + */ + static allocator_type get_allocator() + { + return allocator_type(); + } + + /*! + @brief returns version information on the library + + This function returns a JSON object with information about the library, + including the version number and information on the platform and compiler. + + @return JSON object holding version information + key | description + ----------- | --------------- + `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). + `copyright` | The copyright line for the library as string. + `name` | The name of the library as string. + `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. + `url` | The URL of the project as string. + `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). + + @liveexample{The following code shows an example output of the `meta()` + function.,meta} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @complexity Constant. + + @since 2.1.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json meta() + { + basic_json result; + + result["copyright"] = "(C) 2013-2020 Niels Lohmann"; + result["name"] = "JSON for Modern C++"; + result["url"] = "https://github.com/nlohmann/json"; + result["version"]["string"] = + std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_PATCH); + result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; + result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; + result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; + } + + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref basic_json. + /// @{ + +#if defined(JSON_HAS_CPP_14) + // Use transparent comparator if possible, combined with perfect forwarding + // on find() and count() calls prevents unnecessary string construction. + using object_comparator_t = std::less<>; +#else + using object_comparator_t = std::less; +#endif + + /*! + @brief a type for an object + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: + > An object is an unordered collection of zero or more name/value pairs, + > where a name is a string and a value is a string, number, boolean, null, + > object, or array. + + To store objects in C++, a type is defined by the template parameters + described below. + + @tparam ObjectType the container to store objects (e.g., `std::map` or + `std::unordered_map`) + @tparam StringType the type of the keys or names (e.g., `std::string`). + The comparison function `std::less` is used to order elements + inside the container. + @tparam AllocatorType the allocator to use for objects (e.g., + `std::allocator`) + + #### Default type + + With the default values for @a ObjectType (`std::map`), @a StringType + (`std::string`), and @a AllocatorType (`std::allocator`), the default + value for @a object_t is: + + @code {.cpp} + std::map< + std::string, // key_type + basic_json, // value_type + std::less, // key_compare + std::allocator> // allocator_type + > + @endcode + + #### Behavior + + The choice of @a object_t influences the behavior of the JSON class. With + the default type, objects have the following behavior: + + - When all names are unique, objects will be interoperable in the sense + that all software implementations receiving that object will agree on + the name-value mappings. + - When the names within an object are not unique, it is unspecified which + one of the values for a given key will be chosen. For instance, + `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or + `{"key": 2}`. + - Internally, name/value pairs are stored in lexicographical order of the + names. Objects will also be serialized (see @ref dump) in this order. + For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored + and serialized as `{"a": 2, "b": 1}`. + - When comparing objects, the order of the name/value pairs is irrelevant. + This makes objects interoperable in the sense that they will not be + affected by these differences. For instance, `{"b": 1, "a": 2}` and + `{"a": 2, "b": 1}` will be treated as equal. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the object's limit of nesting is not explicitly constrained. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON object. + + #### Storage + + Objects are stored as pointers in a @ref basic_json type. That is, for any + access to object values, a pointer of type `object_t*` must be + dereferenced. + + @sa @ref array_t -- type for an array value + + @since version 1.0.0 + + @note The order name/value pairs are added to the object is *not* + preserved by the library. Therefore, iterating an object may return + name/value pairs in a different order than they were originally stored. In + fact, keys will be traversed in alphabetical order as `std::map` with + `std::less` is used by default. Please note this behavior conforms to [RFC + 7159](http://rfc7159.net/rfc7159), because any order implements the + specified "unordered" nature of JSON objects. + */ + using object_t = ObjectType>>; + + /*! + @brief a type for an array + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: + > An array is an ordered sequence of zero or more values. + + To store objects in C++, a type is defined by the template parameters + explained below. + + @tparam ArrayType container type to store arrays (e.g., `std::vector` or + `std::list`) + @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) + + #### Default type + + With the default values for @a ArrayType (`std::vector`) and @a + AllocatorType (`std::allocator`), the default value for @a array_t is: + + @code {.cpp} + std::vector< + basic_json, // value_type + std::allocator // allocator_type + > + @endcode + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the maximum depth of nesting. + + In this class, the array's limit of nesting is not explicitly constrained. + However, a maximum depth of nesting may be introduced by the compiler or + runtime environment. A theoretical limit can be queried by calling the + @ref max_size function of a JSON array. + + #### Storage + + Arrays are stored as pointers in a @ref basic_json type. That is, for any + access to array values, a pointer of type `array_t*` must be dereferenced. + + @sa @ref object_t -- type for an object value + + @since version 1.0.0 + */ + using array_t = ArrayType>; + + /*! + @brief a type for a string + + [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: + > A string is a sequence of zero or more Unicode characters. + + To store objects in C++, a type is defined by the template parameter + described below. Unicode values are split by the JSON class into + byte-sized characters during deserialization. + + @tparam StringType the container to store strings (e.g., `std::string`). + Note this container is used for keys/names in objects, see @ref object_t. + + #### Default type + + With the default values for @a StringType (`std::string`), the default + value for @a string_t is: + + @code {.cpp} + std::string + @endcode + + #### Encoding + + Strings are stored in UTF-8 encoding. Therefore, functions like + `std::string::size()` or `std::string::length()` return the number of + bytes in the string rather than the number of characters or glyphs. + + #### String comparison + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > Software implementations are typically required to test names of object + > members for equality. Implementations that transform the textual + > representation into sequences of Unicode code units and then perform the + > comparison numerically, code unit by code unit, are interoperable in the + > sense that implementations will agree in all cases on equality or + > inequality of two strings. For example, implementations that compare + > strings with escaped characters unconverted may incorrectly find that + > `"a\\b"` and `"a\u005Cb"` are not equal. + + This implementation is interoperable as it does compare strings code unit + by code unit. + + #### Storage + + String values are stored as pointers in a @ref basic_json type. That is, + for any access to string values, a pointer of type `string_t*` must be + dereferenced. + + @since version 1.0.0 + */ + using string_t = StringType; + + /*! + @brief a type for a boolean + + [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a + type which differentiates the two literals `true` and `false`. + + To store objects in C++, a type is defined by the template parameter @a + BooleanType which chooses the type to use. + + #### Default type + + With the default values for @a BooleanType (`bool`), the default value for + @a boolean_t is: + + @code {.cpp} + bool + @endcode + + #### Storage + + Boolean values are stored directly inside a @ref basic_json type. + + @since version 1.0.0 + */ + using boolean_t = BooleanType; + + /*! + @brief a type for a number (integer) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store integer numbers in C++, a type is defined by the template + parameter @a NumberIntegerType which chooses the type to use. + + #### Default type + + With the default values for @a NumberIntegerType (`int64_t`), the default + value for @a number_integer_t is: + + @code {.cpp} + int64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `9223372036854775807` (INT64_MAX) and the minimal integer number + that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers + that are out of range will yield over/underflow when used in a + constructor. During deserialization, too large or small integer numbers + will be automatically be stored as @ref number_unsigned_t or @ref + number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange of the exactly supported range [INT64_MIN, + INT64_MAX], this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_integer_t = NumberIntegerType; + + /*! + @brief a type for a number (unsigned) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store unsigned integer numbers in C++, a type is defined by the + template parameter @a NumberUnsignedType which chooses the type to use. + + #### Default type + + With the default values for @a NumberUnsignedType (`uint64_t`), the + default value for @a number_unsigned_t is: + + @code {.cpp} + uint64_t + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in integer literals lead to an interpretation as octal + number. Internally, the value will be stored as decimal number. For + instance, the C++ integer literal `010` will be serialized to `8`. + During deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) specifies: + > An implementation may set limits on the range and precision of numbers. + + When the default type is used, the maximal integer number that can be + stored is `18446744073709551615` (UINT64_MAX) and the minimal integer + number that can be stored is `0`. Integer numbers that are out of range + will yield over/underflow when used in a constructor. During + deserialization, too large or small integer numbers will be automatically + be stored as @ref number_integer_t or @ref number_float_t. + + [RFC 7159](http://rfc7159.net/rfc7159) further states: + > Note that when such software is used, numbers that are integers and are + > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense + > that implementations will agree exactly on their numeric values. + + As this range is a subrange (when considered in conjunction with the + number_integer_t type) of the exactly supported range [0, UINT64_MAX], + this class's integer type is interoperable. + + #### Storage + + Integer number values are stored directly inside a @ref basic_json type. + + @sa @ref number_float_t -- type for number values (floating-point) + @sa @ref number_integer_t -- type for number values (integer) + + @since version 2.0.0 + */ + using number_unsigned_t = NumberUnsignedType; + + /*! + @brief a type for a number (floating-point) + + [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: + > The representation of numbers is similar to that used in most + > programming languages. A number is represented in base 10 using decimal + > digits. It contains an integer component that may be prefixed with an + > optional minus sign, which may be followed by a fraction part and/or an + > exponent part. Leading zeros are not allowed. (...) Numeric values that + > cannot be represented in the grammar below (such as Infinity and NaN) + > are not permitted. + + This description includes both integer and floating-point numbers. + However, C++ allows more precise storage if it is known whether the number + is a signed integer, an unsigned integer or a floating-point number. + Therefore, three different types, @ref number_integer_t, @ref + number_unsigned_t and @ref number_float_t are used. + + To store floating-point numbers in C++, a type is defined by the template + parameter @a NumberFloatType which chooses the type to use. + + #### Default type + + With the default values for @a NumberFloatType (`double`), the default + value for @a number_float_t is: + + @code {.cpp} + double + @endcode + + #### Default behavior + + - The restrictions about leading zeros is not enforced in C++. Instead, + leading zeros in floating-point literals will be ignored. Internally, + the value will be stored as decimal number. For instance, the C++ + floating-point literal `01.2` will be serialized to `1.2`. During + deserialization, leading zeros yield an error. + - Not-a-number (NaN) values will be serialized to `null`. + + #### Limits + + [RFC 7159](http://rfc7159.net/rfc7159) states: + > This specification allows implementations to set limits on the range and + > precision of numbers accepted. Since software that implements IEEE + > 754-2008 binary64 (double precision) numbers is generally available and + > widely used, good interoperability can be achieved by implementations + > that expect no more precision or range than these provide, in the sense + > that implementations will approximate JSON numbers within the expected + > precision. + + This implementation does exactly follow this approach, as it uses double + precision floating-point numbers. Note values smaller than + `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` + will be stored as NaN internally and be serialized to `null`. + + #### Storage + + Floating-point number values are stored directly inside a @ref basic_json + type. + + @sa @ref number_integer_t -- type for number values (integer) + + @sa @ref number_unsigned_t -- type for number values (unsigned integer) + + @since version 1.0.0 + */ + using number_float_t = NumberFloatType; + + /*! + @brief a type for a packed binary type + + This type is a type designed to carry binary data that appears in various + serialized formats, such as CBOR's Major Type 2, MessagePack's bin, and + BSON's generic binary subtype. This type is NOT a part of standard JSON and + exists solely for compatibility with these binary types. As such, it is + simply defined as an ordered sequence of zero or more byte values. + + Additionally, as an implementation detail, the subtype of the binary data is + carried around as a `std::uint8_t`, which is compatible with both of the + binary data formats that use binary subtyping, (though the specific + numbering is incompatible with each other, and it is up to the user to + translate between them). + + [CBOR's RFC 7049](https://tools.ietf.org/html/rfc7049) describes this type + as: + > Major type 2: a byte string. The string's length in bytes is represented + > following the rules for positive integers (major type 0). + + [MessagePack's documentation on the bin type + family](https://github.com/msgpack/msgpack/blob/master/spec.md#bin-format-family) + describes this type as: + > Bin format family stores an byte array in 2, 3, or 5 bytes of extra bytes + > in addition to the size of the byte array. + + [BSON's specifications](http://bsonspec.org/spec.html) describe several + binary types; however, this type is intended to represent the generic binary + type which has the description: + > Generic binary subtype - This is the most commonly used binary subtype and + > should be the 'default' for drivers and tools. + + None of these impose any limitations on the internal representation other + than the basic unit of storage be some type of array whose parts are + decomposable into bytes. + + The default representation of this binary format is a + `std::vector`, which is a very common way to represent a byte + array in modern C++. + + #### Default type + + The default values for @a BinaryType is `std::vector` + + #### Storage + + Binary Arrays are stored as pointers in a @ref basic_json type. That is, + for any access to array values, a pointer of the type `binary_t*` must be + dereferenced. + + #### Notes on subtypes + + - CBOR + - Binary values are represented as byte strings. No subtypes are + supported and will be ignored when CBOR is written. + - MessagePack + - If a subtype is given and the binary array contains exactly 1, 2, 4, 8, + or 16 elements, the fixext family (fixext1, fixext2, fixext4, fixext8) + is used. For other sizes, the ext family (ext8, ext16, ext32) is used. + The subtype is then added as singed 8-bit integer. + - If no subtype is given, the bin family (bin8, bin16, bin32) is used. + - BSON + - If a subtype is given, it is used and added as unsigned 8-bit integer. + - If no subtype is given, the generic binary subtype 0x00 is used. + + @sa @ref binary -- create a binary array + + @since version 3.8.0 + */ + using binary_t = nlohmann::byte_container_with_subtype; + /// @} + + private: + + /// helper for exception-safe object creation + template + JSON_HEDLEY_RETURNS_NON_NULL + static T* create(Args&& ... args) + { + AllocatorType alloc; + using AllocatorTraits = std::allocator_traits>; + + auto deleter = [&](T * object) + { + AllocatorTraits::deallocate(alloc, object, 1); + }; + std::unique_ptr object(AllocatorTraits::allocate(alloc, 1), deleter); + AllocatorTraits::construct(alloc, object.get(), std::forward(args)...); + JSON_ASSERT(object != nullptr); + return object.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref basic_json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to @ref string_t + boolean | boolean | @ref boolean_t + number | number_integer | @ref number_integer_t + number | number_unsigned | @ref number_unsigned_t + number | number_float | @ref number_float_t + binary | binary | pointer to @ref binary_t + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + string_t* string; + /// binary (stored with pointer to save storage) + binary_t* binary; + /// boolean + boolean_t boolean; + /// number (integer) + number_integer_t number_integer; + /// number (unsigned integer) + number_unsigned_t number_unsigned; + /// number (floating-point) + number_float_t number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(boolean_t v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(number_integer_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(number_float_t v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t) + { + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::binary: + { + binary = create(); + break; + } + + case value_t::boolean: + { + boolean = boolean_t(false); + break; + } + + case value_t::number_integer: + { + number_integer = number_integer_t(0); + break; + } + + case value_t::number_unsigned: + { + number_unsigned = number_unsigned_t(0); + break; + } + + case value_t::number_float: + { + number_float = number_float_t(0.0); + break; + } + + case value_t::null: + { + object = nullptr; // silence warning, see #821 + break; + } + + default: + { + object = nullptr; // silence warning, see #821 + if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) + { + JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.9.1")); // LCOV_EXCL_LINE + } + break; + } + } + } + + /// constructor for strings + json_value(const string_t& value) + { + string = create(value); + } + + /// constructor for rvalue strings + json_value(string_t&& value) + { + string = create(std::move(value)); + } + + /// constructor for objects + json_value(const object_t& value) + { + object = create(value); + } + + /// constructor for rvalue objects + json_value(object_t&& value) + { + object = create(std::move(value)); + } + + /// constructor for arrays + json_value(const array_t& value) + { + array = create(value); + } + + /// constructor for rvalue arrays + json_value(array_t&& value) + { + array = create(std::move(value)); + } + + /// constructor for binary arrays + json_value(const typename binary_t::container_type& value) + { + binary = create(value); + } + + /// constructor for rvalue binary arrays + json_value(typename binary_t::container_type&& value) + { + binary = create(std::move(value)); + } + + /// constructor for binary arrays (internal type) + json_value(const binary_t& value) + { + binary = create(value); + } + + /// constructor for rvalue binary arrays (internal type) + json_value(binary_t&& value) + { + binary = create(std::move(value)); + } + + void destroy(value_t t) noexcept + { + // flatten the current json_value to a heap-allocated stack + std::vector stack; + + // move the top-level items to stack + if (t == value_t::array) + { + stack.reserve(array->size()); + std::move(array->begin(), array->end(), std::back_inserter(stack)); + } + else if (t == value_t::object) + { + stack.reserve(object->size()); + for (auto&& it : *object) + { + stack.push_back(std::move(it.second)); + } + } + + while (!stack.empty()) + { + // move the last item to local variable to be processed + basic_json current_item(std::move(stack.back())); + stack.pop_back(); + + // if current_item is array/object, move + // its children to the stack to be processed later + if (current_item.is_array()) + { + std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), + std::back_inserter(stack)); + + current_item.m_value.array->clear(); + } + else if (current_item.is_object()) + { + for (auto&& it : *current_item.m_value.object) + { + stack.push_back(std::move(it.second)); + } + + current_item.m_value.object->clear(); + } + + // it's now safe that current_item get destructed + // since it doesn't have any children + } + + switch (t) + { + case value_t::object: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, object); + std::allocator_traits::deallocate(alloc, object, 1); + break; + } + + case value_t::array: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, array); + std::allocator_traits::deallocate(alloc, array, 1); + break; + } + + case value_t::string: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, string); + std::allocator_traits::deallocate(alloc, string, 1); + break; + } + + case value_t::binary: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, binary); + std::allocator_traits::deallocate(alloc, binary, 1); + break; + } + + default: + { + break; + } + } + } + }; + + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + */ + void assert_invariant() const noexcept + { + JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); + JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); + JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); + JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /*! + @brief parser event types + + The parser callback distinguishes the following events: + - `object_start`: the parser read `{` and started to process a JSON object + - `key`: the parser read a key of a value in an object + - `object_end`: the parser read `}` and finished processing a JSON object + - `array_start`: the parser read `[` and started to process a JSON array + - `array_end`: the parser read `]` and finished processing a JSON array + - `value`: the parser finished reading a JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + @sa @ref parser_callback_t for more information and examples + */ + using parse_event_t = detail::parse_event_t; + + /*! + @brief per-element parser callback type + + With a parser callback function, the result of parsing a JSON text can be + influenced. When passed to @ref parse, it is called on certain events + (passed as @ref parse_event_t via parameter @a event) with a set recursion + depth @a depth and context JSON value @a parsed. The return value of the + callback function is a boolean indicating whether the element that emitted + the callback shall be kept or not. + + We distinguish six scenarios (determined by the event type) in which the + callback function can be called. The following table describes the values + of the parameters @a depth, @a event, and @a parsed. + + parameter @a event | description | parameter @a depth | parameter @a parsed + ------------------ | ----------- | ------------------ | ------------------- + parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded + parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key + parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object + parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded + parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array + parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value + + @image html callback_events.png "Example when certain parse events are triggered" + + Discarding a value (i.e., returning `false`) has different effects + depending on the context in which function was called: + + - Discarded values in structured types are skipped. That is, the parser + will behave as if the discarded value was never read. + - In case a value outside a structured type is skipped, it is replaced + with `null`. This case happens if the top-level element is skipped. + + @param[in] depth the depth of the recursion during parsing + + @param[in] event an event of type parse_event_t indicating the context in + the callback function has been called + + @param[in,out] parsed the current intermediate parse result; note that + writing to this value has no effect for parse_event_t::key events + + @return Whether the JSON value which called the function during parsing + should be kept (`true`) or not (`false`). In the latter case, it is either + skipped completely or replaced by an empty discarded object. + + @sa @ref parse for examples + + @since version 1.0.0 + */ + using parser_callback_t = detail::parser_callback_t; + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref basic_json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /*! + @brief create an empty value with a given type + + Create an empty JSON value with a given type. The value will be default + initialized with an empty value which depends on the type: + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + object | `{}` + array | `[]` + binary | empty array + + @param[in] v the type of the value to create + + @complexity Constant. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows the constructor for different @ref + value_t values,basic_json__value_t} + + @sa @ref clear() -- restores the postcondition of this constructor + + @since version 1.0.0 + */ + basic_json(const value_t v) + : m_type(v), m_value(v) + { + assert_invariant(); + } + + /*! + @brief create a null object + + Create a `null` JSON value. It either takes a null pointer as parameter + (explicitly creating `null`) or no parameter (implicitly creating `null`). + The passed null pointer itself is not read -- it is only used to choose + the right constructor. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @liveexample{The following code shows the constructor with and without a + null pointer parameter.,basic_json__nullptr_t} + + @since version 1.0.0 + */ + basic_json(std::nullptr_t = nullptr) noexcept + : basic_json(value_t::null) + { + assert_invariant(); + } + + /*! + @brief create a JSON value + + This is a "catch all" constructor for all compatible JSON types; that is, + types for which a `to_json()` method exists. The constructor forwards the + parameter @a val to that method (to `json_serializer::to_json` method + with `U = uncvref_t`, to be exact). + + Template type @a CompatibleType includes, but is not limited to, the + following types: + - **arrays**: @ref array_t and all kinds of compatible containers such as + `std::vector`, `std::deque`, `std::list`, `std::forward_list`, + `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, + `std::multiset`, and `std::unordered_multiset` with a `value_type` from + which a @ref basic_json value can be constructed. + - **objects**: @ref object_t and all kinds of compatible associative + containers such as `std::map`, `std::unordered_map`, `std::multimap`, + and `std::unordered_multimap` with a `key_type` compatible to + @ref string_t and a `value_type` from which a @ref basic_json value can + be constructed. + - **strings**: @ref string_t, string literals, and all compatible string + containers can be used. + - **numbers**: @ref number_integer_t, @ref number_unsigned_t, + @ref number_float_t, and all convertible number types such as `int`, + `size_t`, `int64_t`, `float` or `double` can be used. + - **boolean**: @ref boolean_t / `bool` can be used. + - **binary**: @ref binary_t / `std::vector` may be used, + unfortunately because string literals cannot be distinguished from binary + character arrays by the C++ type system, all types compatible with `const + char*` will be directed to the string constructor instead. This is both + for backwards compatibility, and due to the fact that a binary type is not + a standard JSON type. + + See the examples below. + + @tparam CompatibleType a type such that: + - @a CompatibleType is not derived from `std::istream`, + - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move + constructors), + - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) + - @a CompatibleType is not a @ref basic_json nested type (e.g., + @ref json_pointer, @ref iterator, etc ...) + - @ref @ref json_serializer has a + `to_json(basic_json_t&, CompatibleType&&)` method + + @tparam U = `uncvref_t` + + @param[in] val the value to be forwarded to the respective constructor + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @exceptionsafety Depends on the called constructor. For types directly + supported by the library (i.e., all types for which no `to_json()` function + was provided), strong guarantee holds: if an exception is thrown, there are + no changes to any JSON value. + + @liveexample{The following code shows the constructor with several + compatible types.,basic_json__CompatibleType} + + @since version 2.1.0 + */ + template < typename CompatibleType, + typename U = detail::uncvref_t, + detail::enable_if_t < + !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > + basic_json(CompatibleType && val) noexcept(noexcept( + JSONSerializer::to_json(std::declval(), + std::forward(val)))) + { + JSONSerializer::to_json(*this, std::forward(val)); + assert_invariant(); + } + + /*! + @brief create a JSON value from an existing one + + This is a constructor for existing @ref basic_json types. + It does not hijack copy/move constructors, since the parameter has different + template arguments than the current ones. + + The constructor tries to convert the internal @ref m_value of the parameter. + + @tparam BasicJsonType a type such that: + - @a BasicJsonType is a @ref basic_json type. + - @a BasicJsonType has different template arguments than @ref basic_json_t. + + @param[in] val the @ref basic_json value to be converted. + + @complexity Usually linear in the size of the passed @a val, also + depending on the implementation of the called `to_json()` + method. + + @exceptionsafety Depends on the called constructor. For types directly + supported by the library (i.e., all types for which no `to_json()` function + was provided), strong guarantee holds: if an exception is thrown, there are + no changes to any JSON value. + + @since version 3.2.0 + */ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value&& !std::is_same::value, int > = 0 > + basic_json(const BasicJsonType& val) + { + using other_boolean_t = typename BasicJsonType::boolean_t; + using other_number_float_t = typename BasicJsonType::number_float_t; + using other_number_integer_t = typename BasicJsonType::number_integer_t; + using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using other_string_t = typename BasicJsonType::string_t; + using other_object_t = typename BasicJsonType::object_t; + using other_array_t = typename BasicJsonType::array_t; + using other_binary_t = typename BasicJsonType::binary_t; + + switch (val.type()) + { + case value_t::boolean: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_float: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_integer: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_unsigned: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::string: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::object: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::array: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::binary: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::null: + *this = nullptr; + break; + case value_t::discarded: + m_type = value_t::discarded; + break; + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + assert_invariant(); + } + + /*! + @brief create a container (array or object) from an initializer list + + Creates a JSON value of type array or object from the passed initializer + list @a init. In case @a type_deduction is `true` (default), the type of + the JSON value to be created is deducted from the initializer list @a init + according to the following rules: + + 1. If the list is empty, an empty JSON object value `{}` is created. + 2. If the list consists of pairs whose first element is a string, a JSON + object value is created where the first elements of the pairs are + treated as keys and the second elements are as values. + 3. In all other cases, an array is created. + + The rules aim to create the best fit between a C++ initializer list and + JSON values. The rationale is as follows: + + 1. The empty initializer list is written as `{}` which is exactly an empty + JSON object. + 2. C++ has no way of describing mapped types other than to list a list of + pairs. As JSON requires that keys must be of type string, rule 2 is the + weakest constraint one can pose on initializer lists to interpret them + as an object. + 3. In all other cases, the initializer list could not be interpreted as + JSON object type, so interpreting it as JSON array type is safe. + + With the rules described above, the following JSON values cannot be + expressed by an initializer list: + + - the empty array (`[]`): use @ref array(initializer_list_t) + with an empty initializer list in this case + - arrays whose elements satisfy rule 2: use @ref + array(initializer_list_t) with the same initializer list + in this case + + @note When used without parentheses around an empty initializer list, @ref + basic_json() is called instead of this function, yielding the JSON null + value. + + @param[in] init initializer list with JSON values + + @param[in] type_deduction internal parameter; when set to `true`, the type + of the JSON value is deducted from the initializer list @a init; when set + to `false`, the type provided via @a manual_type is forced. This mode is + used by the functions @ref array(initializer_list_t) and + @ref object(initializer_list_t). + + @param[in] manual_type internal parameter; when @a type_deduction is set + to `false`, the created JSON value will use the provided type (only @ref + value_t::array and @ref value_t::object are valid); when @a type_deduction + is set to `true`, this parameter has no effect + + @throw type_error.301 if @a type_deduction is `false`, @a manual_type is + `value_t::object`, but @a init contains an element which is not a pair + whose first element is a string. In this case, the constructor could not + create an object. If @a type_deduction would have be `true`, an array + would have been created. See @ref object(initializer_list_t) + for an example. + + @complexity Linear in the size of the initializer list @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The example below shows how JSON values are created from + initializer lists.,basic_json__list_init_t} + + @sa @ref array(initializer_list_t) -- create a JSON array + value from an initializer list + @sa @ref object(initializer_list_t) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + basic_json(initializer_list_t init, + bool type_deduction = true, + value_t manual_type = value_t::array) + { + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const detail::json_ref& element_ref) + { + return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (!type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) + { + JSON_THROW(type_error::create(301, "cannot create object from initializer list")); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + std::for_each(init.begin(), init.end(), [this](const detail::json_ref& element_ref) + { + auto element = element_ref.moved_or_copied(); + m_value.object->emplace( + std::move(*((*element.m_value.array)[0].m_value.string)), + std::move((*element.m_value.array)[1])); + }); + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init.begin(), init.end()); + } + + assert_invariant(); + } + + /*! + @brief explicitly create a binary array (without subtype) + + Creates a JSON binary array value from a given binary container. Binary + values are part of various binary formats, such as CBOR, MessagePack, and + BSON. This constructor is used to create a value for serialization to those + formats. + + @note Note, this function exists because of the difficulty in correctly + specifying the correct template overload in the standard value ctor, as both + JSON arrays and JSON binary arrays are backed with some form of a + `std::vector`. Because JSON binary arrays are a non-standard extension it + was decided that it would be best to prevent automatic initialization of a + binary array type, for backwards compatibility and so it does not happen on + accident. + + @param[in] init container containing bytes to use as binary type + + @return JSON binary array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @since version 3.8.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = init; + return res; + } + + /*! + @brief explicitly create a binary array (with subtype) + + Creates a JSON binary array value from a given binary container. Binary + values are part of various binary formats, such as CBOR, MessagePack, and + BSON. This constructor is used to create a value for serialization to those + formats. + + @note Note, this function exists because of the difficulty in correctly + specifying the correct template overload in the standard value ctor, as both + JSON arrays and JSON binary arrays are backed with some form of a + `std::vector`. Because JSON binary arrays are a non-standard extension it + was decided that it would be best to prevent automatic initialization of a + binary array type, for backwards compatibility and so it does not happen on + accident. + + @param[in] init container containing bytes to use as binary type + @param[in] subtype subtype to use in MessagePack and BSON + + @return JSON binary array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @since version 3.8.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init, std::uint8_t subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(init, subtype); + return res; + } + + /// @copydoc binary(const typename binary_t::container_type&) + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = std::move(init); + return res; + } + + /// @copydoc binary(const typename binary_t::container_type&, std::uint8_t) + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init, std::uint8_t subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(std::move(init), subtype); + return res; + } + + /*! + @brief explicitly create an array from an initializer list + + Creates a JSON array value from a given initializer list. That is, given a + list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the + initializer list is empty, the empty array `[]` is created. + + @note This function is only needed to express two edge cases that cannot + be realized with the initializer list constructor (@ref + basic_json(initializer_list_t, bool, value_t)). These cases + are: + 1. creating an array whose elements are all pairs whose first element is a + string -- in this case, the initializer list constructor would create an + object, taking the first elements as keys + 2. creating an empty array -- passing the empty initializer list to the + initializer list constructor yields an empty object + + @param[in] init initializer list with JSON values to create an array from + (optional) + + @return JSON array value + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows an example for the `array` + function.,array} + + @sa @ref basic_json(initializer_list_t, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref object(initializer_list_t) -- create a JSON object + value from an initializer list + + @since version 1.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json array(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::array); + } + + /*! + @brief explicitly create an object from an initializer list + + Creates a JSON object value from a given initializer list. The initializer + lists elements must be pairs, and their first elements must be strings. If + the initializer list is empty, the empty object `{}` is created. + + @note This function is only added for symmetry reasons. In contrast to the + related function @ref array(initializer_list_t), there are + no cases which can only be expressed by this function. That is, any + initializer list @a init can also be passed to the initializer list + constructor @ref basic_json(initializer_list_t, bool, value_t). + + @param[in] init initializer list to create an object from (optional) + + @return JSON object value + + @throw type_error.301 if @a init is not a list of pairs whose first + elements are strings. In this case, no object can be created. When such a + value is passed to @ref basic_json(initializer_list_t, bool, value_t), + an array would have been created from the passed initializer list @a init. + See example below. + + @complexity Linear in the size of @a init. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows an example for the `object` + function.,object} + + @sa @ref basic_json(initializer_list_t, bool, value_t) -- + create a JSON value from an initializer list + @sa @ref array(initializer_list_t) -- create a JSON array + value from an initializer list + + @since version 1.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json object(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::object); + } + + /*! + @brief construct an array with count copies of given value + + Constructs a JSON array value by creating @a cnt copies of a passed value. + In case @a cnt is `0`, an empty array is created. + + @param[in] cnt the number of JSON copies of @a val to create + @param[in] val the JSON value to copy + + @post `std::distance(begin(),end()) == cnt` holds. + + @complexity Linear in @a cnt. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The following code shows examples for the @ref + basic_json(size_type\, const basic_json&) + constructor.,basic_json__size_type_basic_json} + + @since version 1.0.0 + */ + basic_json(size_type cnt, const basic_json& val) + : m_type(value_t::array) + { + m_value.array = create(cnt, val); + assert_invariant(); + } + + /*! + @brief construct a JSON container given an iterator range + + Constructs the JSON value with the contents of the range `[first, last)`. + The semantics depends on the different types a JSON value can have: + - In case of a null type, invalid_iterator.206 is thrown. + - In case of other primitive types (number, boolean, or string), @a first + must be `begin()` and @a last must be `end()`. In this case, the value is + copied. Otherwise, invalid_iterator.204 is thrown. + - In case of structured types (array, object), the constructor behaves as + similar versions for `std::vector` or `std::map`; that is, a JSON array + or object is constructed from the values in the range. + + @tparam InputIT an input iterator type (@ref iterator or @ref + const_iterator) + + @param[in] first begin of the range to copy from (included) + @param[in] last end of the range to copy from (excluded) + + @pre Iterators @a first and @a last must be initialized. **This + precondition is enforced with an assertion (see warning).** If + assertions are switched off, a violation of this precondition yields + undefined behavior. + + @pre Range `[first, last)` is valid. Usually, this precondition cannot be + checked efficiently. Only certain edge cases are detected; see the + description of the exceptions below. A violation of this precondition + yields undefined behavior. + + @warning A precondition is enforced with a runtime assertion that will + result in calling `std::abort` if this precondition is not met. + Assertions can be disabled by defining `NDEBUG` at compile time. + See https://en.cppreference.com/w/cpp/error/assert for more + information. + + @throw invalid_iterator.201 if iterators @a first and @a last are not + compatible (i.e., do not belong to the same JSON value). In this case, + the range `[first, last)` is undefined. + @throw invalid_iterator.204 if iterators @a first and @a last belong to a + primitive type (number, boolean, or string), but @a first does not point + to the first element any more. In this case, the range `[first, last)` is + undefined. See example code below. + @throw invalid_iterator.206 if iterators @a first and @a last belong to a + null value. In this case, the range `[first, last)` is undefined. + + @complexity Linear in distance between @a first and @a last. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @liveexample{The example below shows several ways to create JSON values by + specifying a subrange with iterators.,basic_json__InputIt_InputIt} + + @since version 1.0.0 + */ + template < class InputIT, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type = 0 > + basic_json(InputIT first, InputIT last) + { + JSON_ASSERT(first.m_object != nullptr); + JSON_ASSERT(last.m_object != nullptr); + + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range")); + } + break; + } + + default: + break; + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::object: + { + m_value.object = create(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::binary: + { + m_value = *first.m_object->m_value.binary; + break; + } + + default: + JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + + std::string(first.m_object->type_name()))); + } + + assert_invariant(); + } + + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + template, + std::is_same>::value, int> = 0 > + basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} + + /*! + @brief copy constructor + + Creates a copy of a given JSON value. + + @param[in] other the JSON value to copy + + @post `*this == other` + + @complexity Linear in the size of @a other. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes to any JSON value. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + - As postcondition, it holds: `other == basic_json(other)`. + + @liveexample{The following code shows an example for the copy + constructor.,basic_json__basic_json} + + @since version 1.0.0 + */ + basic_json(const basic_json& other) + : m_type(other.m_type) + { + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + case value_t::binary: + { + m_value = *other.m_value.binary; + break; + } + + default: + break; + } + + assert_invariant(); + } + + /*! + @brief move constructor + + Move constructor. Constructs a JSON value with the contents of the given + value @a other using move semantics. It "steals" the resources from @a + other and leaves it as JSON null value. + + @param[in,out] other value to move to this object + + @post `*this` has the same value as @a other before the call. + @post @a other is a JSON null value. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this constructor never throws + exceptions. + + @requirement This function helps `basic_json` satisfying the + [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) + requirements. + + @liveexample{The code below shows the move constructor explicitly called + via std::move.,basic_json__moveconstructor} + + @since version 1.0.0 + */ + basic_json(basic_json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + assert_invariant(); + } + + /*! + @brief copy assignment + + Copy assignment operator. Copies a JSON value via the "copy and swap" + strategy: It is expressed in terms of the copy constructor, destructor, + and the `swap()` member function. + + @param[in] other value to copy from + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + + @liveexample{The code below shows and example for the copy assignment. It + creates a copy of value `a` which is then swapped with `b`. Finally\, the + copy of `a` (which is the null value after the swap) is + destroyed.,basic_json__copyassignment} + + @since version 1.0.0 + */ + basic_json& operator=(basic_json other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + assert_invariant(); + return *this; + } + + /*! + @brief destructor + + Destroys the JSON value and frees all allocated memory. + + @complexity Linear. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is linear. + - All stored elements are destroyed and all memory is freed. + + @since version 1.0.0 + */ + ~basic_json() noexcept + { + assert_invariant(); + m_value.destroy(m_type); + } + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /*! + @brief serialization + + Serialization function for JSON values. The function tries to mimic + Python's `json.dumps()` function, and currently supports its @a indent + and @a ensure_ascii parameters. + + @param[in] indent If indent is nonnegative, then array elements and object + members will be pretty-printed with that indent level. An indent level of + `0` will only insert newlines. `-1` (the default) selects the most compact + representation. + @param[in] indent_char The character to use for indentation if @a indent is + greater than `0`. The default is ` ` (space). + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] error_handler how to react on decoding errors; there are three + possible values: `strict` (throws and exception in case a decoding error + occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), + and `ignore` (ignore invalid UTF-8 sequences during serialization; all + bytes are copied to the output unchanged). + + @return string containing the serialization of the JSON value + + @throw type_error.316 if a string stored inside the JSON value is not + UTF-8 encoded and @a error_handler is set to strict + + @note Binary values are serialized as object containing two keys: + - "bytes": an array of bytes as integers + - "subtype": the subtype as integer or "null" if the binary has no subtype + + @complexity Linear. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @liveexample{The following example shows the effect of different @a indent\, + @a indent_char\, and @a ensure_ascii parameters to the result of the + serialization.,dump} + + @see https://docs.python.org/2/library/json.html#json.dump + + @since version 1.0.0; indentation character @a indent_char, option + @a ensure_ascii and exceptions added in version 3.0.0; error + handlers added in version 3.4.0; serialization of binary values added + in version 3.8.0. + */ + string_t dump(const int indent = -1, + const char indent_char = ' ', + const bool ensure_ascii = false, + const error_handler_t error_handler = error_handler_t::strict) const + { + string_t result; + serializer s(detail::output_adapter(result), indent_char, error_handler); + + if (indent >= 0) + { + s.dump(*this, true, ensure_ascii, static_cast(indent)); + } + else + { + s.dump(*this, false, ensure_ascii, 0); + } + + return result; + } + + /*! + @brief return the type of the JSON value (explicit) + + Return the type of the JSON value as a value from the @ref value_t + enumeration. + + @return the type of the JSON value + Value type | return value + ------------------------- | ------------------------- + null | value_t::null + boolean | value_t::boolean + string | value_t::string + number (integer) | value_t::number_integer + number (unsigned integer) | value_t::number_unsigned + number (floating-point) | value_t::number_float + object | value_t::object + array | value_t::array + binary | value_t::binary + discarded | value_t::discarded + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `type()` for all JSON + types.,type} + + @sa @ref operator value_t() -- return the type of the JSON value (implicit) + @sa @ref type_name() -- return the type as string + + @since version 1.0.0 + */ + constexpr value_t type() const noexcept + { + return m_type; + } + + /*! + @brief return whether type is primitive + + This function returns true if and only if the JSON type is primitive + (string, number, boolean, or null). + + @return `true` if type is primitive (string, number, boolean, or null), + `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_primitive()` for all JSON + types.,is_primitive} + + @sa @ref is_structured() -- returns whether JSON value is structured + @sa @ref is_null() -- returns whether JSON value is `null` + @sa @ref is_string() -- returns whether JSON value is a string + @sa @ref is_boolean() -- returns whether JSON value is a boolean + @sa @ref is_number() -- returns whether JSON value is a number + @sa @ref is_binary() -- returns whether JSON value is a binary array + + @since version 1.0.0 + */ + constexpr bool is_primitive() const noexcept + { + return is_null() || is_string() || is_boolean() || is_number() || is_binary(); + } + + /*! + @brief return whether type is structured + + This function returns true if and only if the JSON type is structured + (array or object). + + @return `true` if type is structured (array or object), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_structured()` for all JSON + types.,is_structured} + + @sa @ref is_primitive() -- returns whether value is primitive + @sa @ref is_array() -- returns whether value is an array + @sa @ref is_object() -- returns whether value is an object + + @since version 1.0.0 + */ + constexpr bool is_structured() const noexcept + { + return is_array() || is_object(); + } + + /*! + @brief return whether value is null + + This function returns true if and only if the JSON value is null. + + @return `true` if type is null, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_null()` for all JSON + types.,is_null} + + @since version 1.0.0 + */ + constexpr bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /*! + @brief return whether value is a boolean + + This function returns true if and only if the JSON value is a boolean. + + @return `true` if type is boolean, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_boolean()` for all JSON + types.,is_boolean} + + @since version 1.0.0 + */ + constexpr bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /*! + @brief return whether value is a number + + This function returns true if and only if the JSON value is a number. This + includes both integer (signed and unsigned) and floating-point values. + + @return `true` if type is number (regardless whether integer, unsigned + integer or floating-type), `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number()` for all JSON + types.,is_number} + + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number() const noexcept + { + return is_number_integer() || is_number_float(); + } + + /*! + @brief return whether value is an integer number + + This function returns true if and only if the JSON value is a signed or + unsigned integer number. This excludes floating-point values. + + @return `true` if type is an integer or unsigned integer number, `false` + otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_integer()` for all + JSON types.,is_number_integer} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 1.0.0 + */ + constexpr bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer || m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is an unsigned integer number + + This function returns true if and only if the JSON value is an unsigned + integer number. This excludes floating-point and signed integer values. + + @return `true` if type is an unsigned integer number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_unsigned()` for all + JSON types.,is_number_unsigned} + + @sa @ref is_number() -- check if value is a number + @sa @ref is_number_integer() -- check if value is an integer or unsigned + integer number + @sa @ref is_number_float() -- check if value is a floating-point number + + @since version 2.0.0 + */ + constexpr bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /*! + @brief return whether value is a floating-point number + + This function returns true if and only if the JSON value is a + floating-point number. This excludes signed and unsigned integer values. + + @return `true` if type is a floating-point number, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_number_float()` for all + JSON types.,is_number_float} + + @sa @ref is_number() -- check if value is number + @sa @ref is_number_integer() -- check if value is an integer number + @sa @ref is_number_unsigned() -- check if value is an unsigned integer + number + + @since version 1.0.0 + */ + constexpr bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /*! + @brief return whether value is an object + + This function returns true if and only if the JSON value is an object. + + @return `true` if type is object, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_object()` for all JSON + types.,is_object} + + @since version 1.0.0 + */ + constexpr bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /*! + @brief return whether value is an array + + This function returns true if and only if the JSON value is an array. + + @return `true` if type is array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_array()` for all JSON + types.,is_array} + + @since version 1.0.0 + */ + constexpr bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /*! + @brief return whether value is a string + + This function returns true if and only if the JSON value is a string. + + @return `true` if type is string, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_string()` for all JSON + types.,is_string} + + @since version 1.0.0 + */ + constexpr bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /*! + @brief return whether value is a binary array + + This function returns true if and only if the JSON value is a binary array. + + @return `true` if type is binary array, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_binary()` for all JSON + types.,is_binary} + + @since version 3.8.0 + */ + constexpr bool is_binary() const noexcept + { + return m_type == value_t::binary; + } + + /*! + @brief return whether value is discarded + + This function returns true if and only if the JSON value was discarded + during parsing with a callback function (see @ref parser_callback_t). + + @note This function will always be `false` for JSON values after parsing. + That is, discarded values can only occur during parsing, but will be + removed when inside a structured value or replaced by null in other cases. + + @return `true` if type is discarded, `false` otherwise. + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies `is_discarded()` for all JSON + types.,is_discarded} + + @since version 1.0.0 + */ + constexpr bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /*! + @brief return the type of the JSON value (implicit) + + Implicitly return the type of the JSON value as a value from the @ref + value_t enumeration. + + @return the type of the JSON value + + @complexity Constant. + + @exceptionsafety No-throw guarantee: this member function never throws + exceptions. + + @liveexample{The following code exemplifies the @ref value_t operator for + all JSON types.,operator__value_t} + + @sa @ref type() -- return the type of the JSON value (explicit) + @sa @ref type_name() -- return the type as string + + @since version 1.0.0 + */ + constexpr operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + boolean_t get_impl(boolean_t* /*unused*/) const + { + if (JSON_HEDLEY_LIKELY(is_boolean())) + { + return m_value.boolean; + } + + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + string_t* get_impl_ptr(string_t* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (binary) + binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /// get a pointer to the value (binary) + constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This function helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `basic_json` or `const basic_json` + + @throw type_error.303 if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // delegate the call to get_ptr<>() + auto ptr = obj.template get_ptr::type>(); + + if (JSON_HEDLEY_LIKELY(ptr != nullptr)) + { + return *ptr; + } + + JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template::type, basic_json_t>::value, + int> = 0> + basic_json get() const + { + return *this; + } + + /*! + @brief get special-case overload + + This overloads converts the current @ref basic_json in a different + @ref basic_json type + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this, converted into @tparam BasicJsonType + + @complexity Depending on the implementation of the called `from_json()` + method. + + @since version 3.2.0 + */ + template < typename BasicJsonType, detail::enable_if_t < + !std::is_same::value&& + detail::is_basic_json::value, int > = 0 > + BasicJsonType get() const + { + return *this; + } + + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const basic_json&)` + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < typename ValueTypeCV, typename ValueType = detail::uncvref_t, + detail::enable_if_t < + !detail::is_basic_json::value && + detail::has_from_json::value && + !detail::has_non_default_from_json::value, + int > = 0 > + ValueType get() const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), std::declval()))) + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + static_assert(std::is_default_constructible::value, + "types must be DefaultConstructible when used with get()"); + + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + } + + /*! + @brief get a value (explicit); special case + + Explicit type conversion between the JSON value and a compatible value + which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + return JSONSerializer::from_json(*this); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json and + - @ref json_serializer has a `from_json()` method of the form + `ValueType from_json(const basic_json&)` + + @note If @ref json_serializer has both overloads of + `from_json()`, this one is chosen. + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @since version 2.1.0 + */ + template < typename ValueTypeCV, typename ValueType = detail::uncvref_t, + detail::enable_if_t < !std::is_same::value && + detail::has_non_default_from_json::value, + int > = 0 > + ValueType get() const noexcept(noexcept( + JSONSerializer::from_json(std::declval()))) + { + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + return JSONSerializer::from_json(*this); + } + + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value. + The value is filled into the input parameter by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType v; + JSONSerializer::from_json(*this, v); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + + @tparam ValueType the input parameter type. + + @return the input parameter, allowing chaining calls. + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get_to} + + @since version 3.3.0 + */ + template < typename ValueType, + detail::enable_if_t < + !detail::is_basic_json::value&& + detail::has_from_json::value, + int > = 0 > + ValueType & get_to(ValueType& v) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + // specialization to allow to call get_to with a basic_json value + // see https://github.com/nlohmann/json/issues/2175 + template::value, + int> = 0> + ValueType & get_to(ValueType& v) const + { + v = *this; + return v; + } + + template < + typename T, std::size_t N, + typename Array = T (&)[N], + detail::enable_if_t < + detail::has_from_json::value, int > = 0 > + Array get_to(T (&v)[N]) const + noexcept(noexcept(JSONSerializer::from_json( + std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + + /*! + @brief get a pointer value (implicit) + + Implicit pointer access to the internally stored JSON value. No copies are + made. + + @warning Writing data to the pointee of the result yields an undefined + state. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. Enforced by a static + assertion. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get_ptr} + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a pointer value (implicit) + @copydoc get_ptr() + */ + template < typename PointerType, typename std::enable_if < + std::is_pointer::value&& + std::is_const::type>::value, int >::type = 0 > + constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get() noexcept -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, int>::type = 0> + constexpr auto get() const noexcept -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + /*! + @brief get a reference value (implicit) + + Implicit reference access to the internally stored JSON value. No copies + are made. + + @warning Writing data to the referee of the result yields an undefined + state. + + @tparam ReferenceType reference type; must be a reference to @ref array_t, + @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or + @ref number_float_t. Enforced by static assertion. + + @return reference to the internally stored JSON value if the requested + reference type @a ReferenceType fits to the JSON value; throws + type_error.303 otherwise + + @throw type_error.303 in case passed type @a ReferenceType is incompatible + with the stored JSON value; see example below + + @complexity Constant. + + @liveexample{The example shows several calls to `get_ref()`.,get_ref} + + @since version 1.1.0 + */ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a reference value (implicit) + @copydoc get_ref() + */ + template < typename ReferenceType, typename std::enable_if < + std::is_reference::value&& + std::is_const::type>::value, int >::type = 0 > + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of @ref string_t + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw type_error.302 in case passed type @a ValueType is incompatible + to the JSON value type (e.g., the JSON value is of type boolean, but a + string is requested); see example below + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + !std::is_pointer::value&& + !std::is_same>::value&& + !std::is_same::value&& + !detail::is_basic_json::value + && !std::is_same>::value +#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) + && !std::is_same::value +#endif + && detail::is_detected::value + , int >::type = 0 > + JSON_EXPLICIT operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /*! + @return reference to the binary value + + @throw type_error.302 if the value is not binary + + @sa @ref is_binary() to check if the value is binary + + @since version 3.8.0 + */ + binary_t& get_binary() + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()))); + } + + return *get_ptr(); + } + + /// @copydoc get_binary() + const binary_t& get_binary() const + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()))); + } + + return *get_ptr(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /*! + @brief access specified array element with bounds checking + + Returns a reference to the element at specified location @a idx, with + bounds checking. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__size_type} + */ + reference at(size_type idx) + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); + } + } + + /*! + @brief access specified array element with bounds checking + + Returns a const reference to the element at specified location @a idx, + with bounds checking. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.304 if the JSON value is not an array; in this case, + calling `at` with an index makes no sense. See example below. + @throw out_of_range.401 if the index @a idx is out of range of the array; + that is, `idx >= size()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 1.0.0 + + @liveexample{The example below shows how array elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__size_type_const} + */ + const_reference at(size_type idx) const + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a reference to the element at with specified key @a key, with + bounds checking. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read and + written using `at()`. It also demonstrates the different exceptions that + can be thrown.,at__object_t_key_type} + */ + reference at(const typename object_t::key_type& key) + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); + } + } + + /*! + @brief access specified object element with bounds checking + + Returns a const reference to the element at with specified key @a key, + with bounds checking. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @throw type_error.304 if the JSON value is not an object; in this case, + calling `at` with a key makes no sense. See example below. + @throw out_of_range.403 if the key @a key is is not stored in the object; + that is, `find(key) == end()`. See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Logarithmic in the size of the container. + + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + + @liveexample{The example below shows how object elements can be read using + `at()`. It also demonstrates the different exceptions that can be thrown., + at__object_t_key_type_const} + */ + const_reference at(const typename object_t::key_type& key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); + } + } + + /*! + @brief access specified array element + + Returns a reference to the element at specified location @a idx. + + @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), + then the array is silently filled up with `null` values to make `idx` a + valid reference to the last stored element. + + @param[in] idx index of the element to access + + @return reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array or null; in that + cases, using the [] operator with an index makes no sense. + + @complexity Constant if @a idx is in the range of the array. Otherwise + linear in `idx - size()`. + + @liveexample{The example below shows how array elements can be read and + written using `[]` operator. Note the addition of `null` + values.,operatorarray__size_type} + + @since version 1.0.0 + */ + reference operator[](size_type idx) + { + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { + m_value.array->insert(m_value.array->end(), + idx - m_value.array->size() + 1, + basic_json()); + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); + } + + /*! + @brief access specified array element + + Returns a const reference to the element at specified location @a idx. + + @param[in] idx index of the element to access + + @return const reference to the element at index @a idx + + @throw type_error.305 if the JSON value is not an array; in that case, + using the [] operator with an index makes no sense. + + @complexity Constant. + + @liveexample{The example below shows how array elements can be read using + the `[]` operator.,operatorarray__size_type_const} + + @since version 1.0.0 + */ + const_reference operator[](size_type idx) const + { + // const operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + reference operator[](const typename object_t::key_type& key) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->operator[](key); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that case, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.0.0 + */ + const_reference operator[](const typename object_t::key_type& key) const + { + // const operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); + } + + /*! + @brief access specified object element + + Returns a reference to the element at with specified key @a key. + + @note If @a key is not found in the object, then it is silently added to + the object and filled with a `null` value to make `key` a valid reference. + In case the value was `null` before, it is converted to an object. + + @param[in] key key of the element to access + + @return reference to the element at key @a key + + @throw type_error.305 if the JSON value is not an object or null; in that + cases, using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read and + written using the `[]` operator.,operatorarray__key_type} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + reference operator[](T* key) + { + // implicitly convert null to object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->operator[](key); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); + } + + /*! + @brief read-only access specified object element + + Returns a const reference to the element at with specified key @a key. No + bounds checking is performed. + + @warning If the element with key @a key does not exist, the behavior is + undefined. + + @param[in] key key of the element to access + + @return const reference to the element at key @a key + + @pre The element with key @a key must exist. **This precondition is + enforced with an assertion.** + + @throw type_error.305 if the JSON value is not an object; in that case, + using the [] operator with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be read using + the `[]` operator.,operatorarray__key_type_const} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref value() for access by value with a default value + + @since version 1.1.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + const_reference operator[](T* key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); + } + + /*! + @brief access specified object element with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(key); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const typename object_t::key_type&), this function + does not throw if the given key @a key was not found. + + @note Unlike @ref operator[](const typename object_t::key_type& key), this + function does not implicitly add an element to the position defined by @a + key. This function is furthermore also applicable to const objects. + + @param[in] key key of the element to access + @param[in] default_value the value to return if @a key is not found + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.302 if @a default_value does not match the type of the + value at @a key + @throw type_error.306 if the JSON value is not an object; in that case, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value} + + @sa @ref at(const typename object_t::key_type&) for access by reference + with range checking + @sa @ref operator[](const typename object_t::key_type&) for unchecked + access by reference + + @since version 1.0.0 + */ + // using std::is_convertible in a std::enable_if will fail when using explicit conversions + template < class ValueType, typename std::enable_if < + detail::is_getable::value + && !std::is_same::value, int >::type = 0 > + ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return it->template get(); + } + + return default_value; + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const + */ + string_t value(const typename object_t::key_type& key, const char* default_value) const + { + return value(key, string_t(default_value)); + } + + /*! + @brief access specified object element via JSON Pointer with default value + + Returns either a copy of an object's element at the specified key @a key + or a given default value if no element with key @a key exists. + + The function is basically equivalent to executing + @code {.cpp} + try { + return at(ptr); + } catch(out_of_range) { + return default_value; + } + @endcode + + @note Unlike @ref at(const json_pointer&), this function does not throw + if the given key @a key was not found. + + @param[in] ptr a JSON pointer to the element to access + @param[in] default_value the value to return if @a ptr found no value + + @tparam ValueType type compatible to JSON values, for instance `int` for + JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for + JSON arrays. Note the type of the expected value at @a key and the default + value @a default_value must be compatible. + + @return copy of the element at key @a key or @a default_value if @a key + is not found + + @throw type_error.302 if @a default_value does not match the type of the + value at @a ptr + @throw type_error.306 if the JSON value is not an object; in that case, + using `value()` with a key makes no sense. + + @complexity Logarithmic in the size of the container. + + @liveexample{The example below shows how object elements can be queried + with a default value.,basic_json__value_ptr} + + @sa @ref operator[](const json_pointer&) for unchecked access by reference + + @since version 2.0.2 + */ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this).template get(); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + return default_value; + } + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); + } + + /*! + @brief overload for a default value of type const char* + @copydoc basic_json::value(const json_pointer&, ValueType) const + */ + JSON_HEDLEY_NON_NULL(3) + string_t value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, string_t(default_value)); + } + + /*! + @brief access the first element + + Returns a reference to the first element in the container. For a JSON + container `c`, the expression `c.front()` is equivalent to `*c.begin()`. + + @return In case of a structured type (array or object), a reference to the + first element is returned. In case of number, string, boolean, or binary + values, a reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on `null` value + + @liveexample{The following code shows an example for `front()`.,front} + + @sa @ref back() -- access the last element + + @since version 1.0.0 + */ + reference front() + { + return *begin(); + } + + /*! + @copydoc basic_json::front() + */ + const_reference front() const + { + return *cbegin(); + } + + /*! + @brief access the last element + + Returns a reference to the last element in the container. For a JSON + container `c`, the expression `c.back()` is equivalent to + @code {.cpp} + auto tmp = c.end(); + --tmp; + return *tmp; + @endcode + + @return In case of a structured type (array or object), a reference to the + last element is returned. In case of number, string, boolean, or binary + values, a reference to the value is returned. + + @complexity Constant. + + @pre The JSON value must not be `null` (would throw `std::out_of_range`) + or an empty array or object (undefined behavior, **guarded by + assertions**). + @post The JSON value remains unchanged. + + @throw invalid_iterator.214 when called on a `null` value. See example + below. + + @liveexample{The following code shows an example for `back()`.,back} + + @sa @ref front() -- access the first element + + @since version 1.0.0 + */ + reference back() + { + auto tmp = end(); + --tmp; + return *tmp; + } + + /*! + @copydoc basic_json::back() + */ + const_reference back() const + { + auto tmp = cend(); + --tmp; + return *tmp; + } + + /*! + @brief remove element given an iterator + + Removes the element specified by iterator @a pos. The iterator @a pos must + be valid and dereferenceable. Thus the `end()` iterator (which is valid, + but is not dereferenceable) cannot be used as a value for @a pos. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] pos iterator to the element to remove + @return Iterator following the last removed element. If the iterator @a + pos refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.202 if called on an iterator which does not belong + to the current JSON value; example: `"iterator does not fit current + value"` + @throw invalid_iterator.205 if called on a primitive type with invalid + iterator (i.e., any iterator which is not `begin()`); example: `"iterator + out of range"` + + @complexity The complexity depends on the type: + - objects: amortized constant + - arrays: linear in distance between @a pos and the end of the container + - strings and binary: linear in the length of the member + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType} + + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType pos) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) + { + JSON_THROW(invalid_iterator::create(205, "iterator out of range")); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); + break; + } + + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); + } + + return result; + } + + /*! + @brief remove elements given an iterator range + + Removes the element specified by the range `[first; last)`. The iterator + @a first does not need to be dereferenceable if `first == last`: erasing + an empty range is a no-op. + + If called on a primitive type other than `null`, the resulting JSON value + will be `null`. + + @param[in] first iterator to the beginning of the range to remove + @param[in] last iterator past the end of the range to remove + @return Iterator following the last removed element. If the iterator @a + second refers to the last element, the `end()` iterator is returned. + + @tparam IteratorType an @ref iterator or @ref const_iterator + + @post Invalidates iterators and references at or after the point of the + erase, including the `end()` iterator. + + @throw type_error.307 if called on a `null` value; example: `"cannot use + erase() with null"` + @throw invalid_iterator.203 if called on iterators which does not belong + to the current JSON value; example: `"iterators do not fit current value"` + @throw invalid_iterator.204 if called on a primitive type with invalid + iterators (i.e., if `first != begin()` and `last != end()`); example: + `"iterators out of range"` + + @complexity The complexity depends on the type: + - objects: `log(size()) + std::distance(first, last)` + - arrays: linear in the distance between @a first and @a last, plus linear + in the distance between @a last and end of the container + - strings and binary: linear in the length of the member + - other types: constant + + @liveexample{The example shows the result of `erase()` for different JSON + types.,erase__IteratorType_IteratorType} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) + { + JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range")); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); + } + + return result; + } + + /*! + @brief remove element from a JSON object given a key + + Removes elements from a JSON object with the key value @a key. + + @param[in] key value of the elements to remove + + @return Number of elements removed. If @a ObjectType is the default + `std::map` type, the return value will always be `0` (@a key was not + found) or `1` (@a key was found). + + @post References and iterators to the erased elements are invalidated. + Other references and iterators are not affected. + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + + @complexity `log(size()) + count(key)` + + @liveexample{The example shows the effect of `erase()`.,erase__key_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const size_type) -- removes the element from an array at + the given index + + @since version 1.0.0 + */ + size_type erase(const typename object_t::key_type& key) + { + // this erase only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->erase(key); + } + + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); + } + + /*! + @brief remove element from a JSON array given an index + + Removes element from a JSON array at the index @a idx. + + @param[in] idx index of the element to remove + + @throw type_error.307 when called on a type other than JSON object; + example: `"cannot use erase() with null"` + @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 + is out of range"` + + @complexity Linear in distance between @a idx and the end of the container. + + @liveexample{The example shows the effect of `erase()`.,erase__size_type} + + @sa @ref erase(IteratorType) -- removes the element at a given position + @sa @ref erase(IteratorType, IteratorType) -- removes the elements in + the given range + @sa @ref erase(const typename object_t::key_type&) -- removes the element + from an object at the given key + + @since version 1.0.0 + */ + void erase(const size_type idx) + { + // this erase only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + if (JSON_HEDLEY_UNLIKELY(idx >= size())) + { + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); + } + } + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /*! + @brief find an element in a JSON object + + Finds an element in a JSON object with key equivalent to @a key. If the + element is not found or the JSON value is not an object, end() is + returned. + + @note This method always returns @ref end() when executed on a JSON type + that is not an object. + + @param[in] key key value of the element to search for. + + @return Iterator to an element with key equivalent to @a key. If no such + element is found or the JSON value is not an object, past-the-end (see + @ref end()) iterator is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `find()` is used.,find__key_type} + + @sa @ref contains(KeyT&&) const -- checks whether a key exists + + @since version 1.0.0 + */ + template + iterator find(KeyT&& key) + { + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /*! + @brief find an element in a JSON object + @copydoc find(KeyT&&) + */ + template + const_iterator find(KeyT&& key) const + { + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /*! + @brief returns the number of occurrences of a key in a JSON object + + Returns the number of elements with key @a key. If ObjectType is the + default `std::map` type, the return value will always be `0` (@a key was + not found) or `1` (@a key was found). + + @note This method always returns `0` when executed on a JSON type that is + not an object. + + @param[in] key key value of the element to count + + @return Number of elements with key @a key. If the JSON value is not an + object, the return value will be `0`. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The example shows how `count()` is used.,count} + + @since version 1.0.0 + */ + template + size_type count(KeyT&& key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(std::forward(key)) : 0; + } + + /*! + @brief check the existence of an element in a JSON object + + Check whether an element exists in a JSON object with key equivalent to + @a key. If the element is not found or the JSON value is not an object, + false is returned. + + @note This method always returns false when executed on a JSON type + that is not an object. + + @param[in] key key value to check its existence. + + @return true if an element with specified @a key exists. If no such + element with such key is found or the JSON value is not an object, + false is returned. + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The following code shows an example for `contains()`.,contains} + + @sa @ref find(KeyT&&) -- returns an iterator to an object element + @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer + + @since version 3.6.0 + */ + template < typename KeyT, typename std::enable_if < + !std::is_same::type, json_pointer>::value, int >::type = 0 > + bool contains(KeyT && key) const + { + return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); + } + + /*! + @brief check the existence of an element in a JSON object given a JSON pointer + + Check whether the given JSON pointer @a ptr can be resolved in the current + JSON value. + + @note This method can be executed on any JSON value type. + + @param[in] ptr JSON pointer to check its existence. + + @return true if the JSON pointer can be resolved to a stored value, false + otherwise. + + @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + + @complexity Logarithmic in the size of the JSON object. + + @liveexample{The following code shows an example for `contains()`.,contains_json_pointer} + + @sa @ref contains(KeyT &&) const -- checks the existence of a key + + @since version 3.7.0 + */ + bool contains(const json_pointer& ptr) const + { + return ptr.contains(this); + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /*! + @brief returns an iterator to the first element + + Returns an iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `begin()`.,begin} + + @sa @ref cbegin() -- returns a const iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /*! + @copydoc basic_json::cbegin() + */ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /*! + @brief returns a const iterator to the first element + + Returns a const iterator to the first element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator to the first element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).begin()`. + + @liveexample{The following code shows an example for `cbegin()`.,cbegin} + + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref end() -- returns an iterator to the end + @sa @ref cend() -- returns a const iterator to the end + + @since version 1.0.0 + */ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /*! + @brief returns an iterator to one past the last element + + Returns an iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + + @liveexample{The following code shows an example for `end()`.,end} + + @sa @ref cend() -- returns a const iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /*! + @copydoc basic_json::cend() + */ + const_iterator end() const noexcept + { + return cend(); + } + + /*! + @brief returns a const iterator to one past the last element + + Returns a const iterator to one past the last element. + + @image html range-begin-end.svg "Illustration from cppreference.com" + + @return const iterator one past the last element + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).end()`. + + @liveexample{The following code shows an example for `cend()`.,cend} + + @sa @ref end() -- returns an iterator to the end + @sa @ref begin() -- returns an iterator to the beginning + @sa @ref cbegin() -- returns a const iterator to the beginning + + @since version 1.0.0 + */ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + /*! + @brief returns an iterator to the reverse-beginning + + Returns an iterator to the reverse-beginning; that is, the last element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(end())`. + + @liveexample{The following code shows an example for `rbegin()`.,rbegin} + + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + /*! + @copydoc basic_json::crbegin() + */ + const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + /*! + @brief returns an iterator to the reverse-end + + Returns an iterator to the reverse-end; that is, one before the first + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `reverse_iterator(begin())`. + + @liveexample{The following code shows an example for `rend()`.,rend} + + @sa @ref crend() -- returns a const reverse iterator to the end + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + reverse_iterator rend() noexcept + { + return reverse_iterator(begin()); + } + + /*! + @copydoc basic_json::crend() + */ + const_reverse_iterator rend() const noexcept + { + return crend(); + } + + /*! + @brief returns a const reverse iterator to the last element + + Returns a const iterator to the reverse-beginning; that is, the last + element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rbegin()`. + + @liveexample{The following code shows an example for `crbegin()`.,crbegin} + + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref crend() -- returns a const reverse iterator to the end + + @since version 1.0.0 + */ + const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + /*! + @brief returns a const reverse iterator to one before the first + + Returns a const reverse iterator to the reverse-end; that is, one before + the first element. + + @image html range-rbegin-rend.svg "Illustration from cppreference.com" + + @complexity Constant. + + @requirement This function helps `basic_json` satisfying the + [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) + requirements: + - The complexity is constant. + - Has the semantics of `const_cast(*this).rend()`. + + @liveexample{The following code shows an example for `crend()`.,crend} + + @sa @ref rend() -- returns a reverse iterator to the end + @sa @ref rbegin() -- returns a reverse iterator to the beginning + @sa @ref crbegin() -- returns a const reverse iterator to the beginning + + @since version 1.0.0 + */ + const_reverse_iterator crend() const noexcept + { + return const_reverse_iterator(cbegin()); + } + + public: + /*! + @brief wrapper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + For loop without iterator_wrapper: + + @code{cpp} + for (auto it = j_object.begin(); it != j_object.end(); ++it) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + Range-based for loop without iterator proxy: + + @code{cpp} + for (auto it : j_object) + { + // "it" is of type json::reference and has no key() member + std::cout << "value: " << it << '\n'; + } + @endcode + + Range-based for loop with iterator proxy: + + @code{cpp} + for (auto it : json::iterator_wrapper(j_object)) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + @note When iterating over an array, `key()` will return the index of the + element as string (see example). + + @param[in] ref reference to a JSON value + @return iteration proxy object wrapping @a ref with an interface to use in + range-based for loops + + @liveexample{The following code shows how the wrapper is used,iterator_wrapper} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @note The name of this function is not yet final and may change in the + future. + + @deprecated This stream operator is deprecated and will be removed in + future 4.0.0 of the library. Please use @ref items() instead; + that is, replace `json::iterator_wrapper(j)` with `j.items()`. + */ + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(reference ref) noexcept + { + return ref.items(); + } + + /*! + @copydoc iterator_wrapper(reference) + */ + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(const_reference ref) noexcept + { + return ref.items(); + } + + /*! + @brief helper to access iterator member functions in range-based for + + This function allows to access @ref iterator::key() and @ref + iterator::value() during range-based for loops. In these loops, a + reference to the JSON values is returned, so there is no access to the + underlying iterator. + + For loop without `items()` function: + + @code{cpp} + for (auto it = j_object.begin(); it != j_object.end(); ++it) + { + std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; + } + @endcode + + Range-based for loop without `items()` function: + + @code{cpp} + for (auto it : j_object) + { + // "it" is of type json::reference and has no key() member + std::cout << "value: " << it << '\n'; + } + @endcode + + Range-based for loop with `items()` function: + + @code{cpp} + for (auto& el : j_object.items()) + { + std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; + } + @endcode + + The `items()` function also allows to use + [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) + (C++17): + + @code{cpp} + for (auto& [key, val] : j_object.items()) + { + std::cout << "key: " << key << ", value:" << val << '\n'; + } + @endcode + + @note When iterating over an array, `key()` will return the index of the + element as string (see example). For primitive types (e.g., numbers), + `key()` returns an empty string. + + @warning Using `items()` on temporary objects is dangerous. Make sure the + object's lifetime exeeds the iteration. See + for more + information. + + @return iteration proxy object wrapping @a ref with an interface to use in + range-based for loops + + @liveexample{The following code shows how the function is used.,items} + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 3.1.0, structured bindings support since 3.5.0. + */ + iteration_proxy items() noexcept + { + return iteration_proxy(*this); + } + + /*! + @copydoc items() + */ + iteration_proxy items() const noexcept + { + return iteration_proxy(*this); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /*! + @brief checks whether the container is empty. + + Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `true` + boolean | `false` + string | `false` + number | `false` + binary | `false` + object | result of function `object_t::empty()` + array | result of function `array_t::empty()` + + @liveexample{The following code uses `empty()` to check if a JSON + object contains any elements.,empty} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `empty()` functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @note This function does not return whether a string stored as JSON value + is empty - it returns whether the JSON container itself is empty which is + false in the case of a string. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `begin() == end()`. + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + bool empty() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + default: + { + // all other types are nonempty + return false; + } + } + } + + /*! + @brief returns the number of elements + + Returns the number of elements in a JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` + boolean | `1` + string | `1` + number | `1` + binary | `1` + object | result of function object_t::size() + array | result of function array_t::size() + + @liveexample{The following code calls `size()` on the different value + types.,size} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their size() functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @note This function does not return the length of a string stored as JSON + value - it returns the number of elements in the JSON value which is 1 in + the case of a string. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of `std::distance(begin(), end())`. + + @sa @ref empty() -- checks whether the container is empty + @sa @ref max_size() -- returns the maximal number of elements + + @since version 1.0.0 + */ + size_type size() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + default: + { + // all other types have size 1 + return 1; + } + } + } + + /*! + @brief returns the maximum possible number of elements + + Returns the maximum number of elements a JSON value is able to hold due to + system or library implementation limitations, i.e. `std::distance(begin(), + end())` for the JSON value. + + @return The return value depends on the different types and is + defined as follows: + Value type | return value + ----------- | ------------- + null | `0` (same as `size()`) + boolean | `1` (same as `size()`) + string | `1` (same as `size()`) + number | `1` (same as `size()`) + binary | `1` (same as `size()`) + object | result of function `object_t::max_size()` + array | result of function `array_t::max_size()` + + @liveexample{The following code calls `max_size()` on the different value + types. Note the output is implementation specific.,max_size} + + @complexity Constant, as long as @ref array_t and @ref object_t satisfy + the Container concept; that is, their `max_size()` functions have constant + complexity. + + @iterators No changes. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @requirement This function helps `basic_json` satisfying the + [Container](https://en.cppreference.com/w/cpp/named_req/Container) + requirements: + - The complexity is constant. + - Has the semantics of returning `b.size()` where `b` is the largest + possible JSON value. + + @sa @ref size() -- returns the number of elements + + @since version 1.0.0 + */ + size_type max_size() const noexcept + { + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to object_t::max_size() + return m_value.object->max_size(); + } + + default: + { + // all other types have max_size() == size() + return size(); + } + } + } + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /*! + @brief clears the contents + + Clears the content of a JSON value and resets it to the default value as + if @ref basic_json(value_t) would have been called with the current value + type from @ref type(): + + Value type | initial value + ----------- | ------------- + null | `null` + boolean | `false` + string | `""` + number | `0` + binary | An empty byte vector + object | `{}` + array | `[]` + + @post Has the same effect as calling + @code {.cpp} + *this = basic_json(type()); + @endcode + + @liveexample{The example below shows the effect of `clear()` to different + JSON types.,clear} + + @complexity Linear in the size of the JSON value. + + @iterators All iterators, pointers and references related to this container + are invalidated. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @sa @ref basic_json(value_t) -- constructor that creates an object with the + same value than calling `clear()` + + @since version 1.0.0 + */ + void clear() noexcept + { + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::binary: + { + m_value.binary->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + default: + break; + } + } + + /*! + @brief add an object to an array + + Appends the given element @a val to the end of the JSON value. If the + function is called on a JSON null value, an empty array is created before + appending @a val. + + @param[in] val the value to add to the JSON array + + @throw type_error.308 when called on a type other than JSON array or + null; example: `"cannot use push_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON array. Note how the `null` value was silently + converted to a JSON array.,push_back} + + @since version 1.0.0 + */ + void push_back(basic_json&& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + m_value.array->push_back(std::move(val)); + // if val is moved from, basic_json move constructor marks it null so we do not call the destructor + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(basic_json&& val) + { + push_back(std::move(val)); + return *this; + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + void push_back(const basic_json& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + m_value.array->push_back(val); + } + + /*! + @brief add an object to an array + @copydoc push_back(basic_json&&) + */ + reference operator+=(const basic_json& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + Inserts the given element @a val to the JSON object. If the function is + called on a JSON null value, an empty object is created before inserting + @a val. + + @param[in] val the value to add to the JSON object + + @throw type_error.308 when called on a type other than JSON object or + null; example: `"cannot use push_back() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `push_back()` and `+=` can be used to + add elements to a JSON object. Note how the `null` value was silently + converted to a JSON object.,push_back__object_t__value} + + @since version 1.0.0 + */ + void push_back(const typename object_t::value_type& val) + { + // push_back only works for null objects or objects + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array + m_value.object->insert(val); + } + + /*! + @brief add an object to an object + @copydoc push_back(const typename object_t::value_type&) + */ + reference operator+=(const typename object_t::value_type& val) + { + push_back(val); + return *this; + } + + /*! + @brief add an object to an object + + This function allows to use `push_back` with an initializer list. In case + + 1. the current value is an object, + 2. the initializer list @a init contains only two elements, and + 3. the first element of @a init is a string, + + @a init is converted into an object element and added using + @ref push_back(const typename object_t::value_type&). Otherwise, @a init + is converted to a JSON value and added using @ref push_back(basic_json&&). + + @param[in] init an initializer list + + @complexity Linear in the size of the initializer list @a init. + + @note This function is required to resolve an ambiguous overload error, + because pairs like `{"key", "value"}` can be both interpreted as + `object_t::value_type` or `std::initializer_list`, see + https://github.com/nlohmann/json/issues/235 for more information. + + @liveexample{The example shows how initializer lists are treated as + objects when possible.,push_back__initializer_list} + */ + void push_back(initializer_list_t init) + { + if (is_object() && init.size() == 2 && (*init.begin())->is_string()) + { + basic_json&& key = init.begin()->moved_or_copied(); + push_back(typename object_t::value_type( + std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); + } + else + { + push_back(basic_json(init)); + } + } + + /*! + @brief add an object to an object + @copydoc push_back(initializer_list_t) + */ + reference operator+=(initializer_list_t init) + { + push_back(init); + return *this; + } + + /*! + @brief add an object to an array + + Creates a JSON value from the passed parameters @a args to the end of the + JSON value. If the function is called on a JSON null value, an empty array + is created before appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @return reference to the inserted element + + @throw type_error.311 when called on a type other than JSON array or + null; example: `"cannot use emplace_back() with number"` + + @complexity Amortized constant. + + @liveexample{The example shows how `push_back()` can be used to add + elements to a JSON array. Note how the `null` value was silently converted + to a JSON array.,emplace_back} + + @since version 2.0.8, returns reference since 3.7.0 + */ + template + reference emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) +#ifdef JSON_HAS_CPP_17 + return m_value.array->emplace_back(std::forward(args)...); +#else + m_value.array->emplace_back(std::forward(args)...); + return m_value.array->back(); +#endif + } + + /*! + @brief add an object to an object if key does not exist + + Inserts a new element into a JSON object constructed in-place with the + given @a args if there is no element with the key in the container. If the + function is called on a JSON null value, an empty object is created before + appending the value created from @a args. + + @param[in] args arguments to forward to a constructor of @ref basic_json + @tparam Args compatible types to create a @ref basic_json object + + @return a pair consisting of an iterator to the inserted element, or the + already-existing element if no insertion happened, and a bool + denoting whether the insertion took place. + + @throw type_error.311 when called on a type other than JSON object or + null; example: `"cannot use emplace() with number"` + + @complexity Logarithmic in the size of the container, O(log(`size()`)). + + @liveexample{The example shows how `emplace()` can be used to add elements + to a JSON object. Note how the `null` value was silently converted to a + JSON object. Further note how no value is added if there was already one + value stored with the same key.,emplace} + + @since version 2.0.8 + */ + template + std::pair emplace(Args&& ... args) + { + // emplace only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace(std::forward(args)...); + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /// Helper for insertion of an iterator + /// @note: This uses std::distance to support GCC 4.8, + /// see https://github.com/nlohmann/json/pull/1257 + template + iterator insert_iterator(const_iterator pos, Args&& ... args) + { + iterator result(this); + JSON_ASSERT(m_value.array != nullptr); + + auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); + m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); + result.m_it.array_iterator = m_value.array->begin() + insert_pos; + + // This could have been written as: + // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); + // but the return value of insert is missing in GCC 4.8, so it is written this way instead. + + return result; + } + + /*! + @brief inserts element + + Inserts element @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] val element to insert + @return iterator pointing to the inserted @a val. + + @throw type_error.309 if called on JSON values other than arrays; + example: `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Constant plus linear in the distance between @a pos and end of + the container. + + @liveexample{The example shows how `insert()` is used.,insert} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + return insert_iterator(pos, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); + } + + /*! + @brief inserts element + @copydoc insert(const_iterator, const basic_json&) + */ + iterator insert(const_iterator pos, basic_json&& val) + { + return insert(pos, val); + } + + /*! + @brief inserts elements + + Inserts @a cnt copies of @a val before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] cnt number of copies of @a val to insert + @param[in] val element to insert + @return iterator pointing to the first element inserted, or @a pos if + `cnt==0` + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @complexity Linear in @a cnt plus linear in the distance between @a pos + and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__count} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, size_type cnt, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + return insert_iterator(pos, cnt, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); + } + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)` before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + @throw invalid_iterator.211 if @a first or @a last are iterators into + container for which insert is called; example: `"passed iterators may not + belong to container"` + + @return iterator pointing to the first element inserted, or @a pos if + `first==last` + + @complexity Linear in `std::distance(first, last)` plus linear in the + distance between @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__range} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, const_iterator first, const_iterator last) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); + } + + if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) + { + JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); + } + + // insert to array and return iterator + return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); + } + + /*! + @brief inserts elements + + Inserts elements from initializer list @a ilist before iterator @a pos. + + @param[in] pos iterator before which the content will be inserted; may be + the end() iterator + @param[in] ilist initializer list to insert the values from + + @throw type_error.309 if called on JSON values other than arrays; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if @a pos is not an iterator of *this; + example: `"iterator does not fit current value"` + + @return iterator pointing to the first element inserted, or @a pos if + `ilist` is empty + + @complexity Linear in `ilist.size()` plus linear in the distance between + @a pos and end of the container. + + @liveexample{The example shows how `insert()` is used.,insert__ilist} + + @since version 1.0.0 + */ + iterator insert(const_iterator pos, initializer_list_t ilist) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); + } + + // insert to array and return iterator + return insert_iterator(pos, ilist.begin(), ilist.end()); + } + + /*! + @brief inserts elements + + Inserts elements from range `[first, last)`. + + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.309 if called on JSON values other than objects; example: + `"cannot use insert() with string"` + @throw invalid_iterator.202 if iterator @a first or @a last does does not + point to an object; example: `"iterators first and last must point to + objects"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + + @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number + of elements to insert. + + @liveexample{The example shows how `insert()` is used.,insert__range_object} + + @since version 3.0.0 + */ + void insert(const_iterator first, const_iterator last) + { + // insert only works for objects + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); + } + + m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); + } + + /*! + @brief updates a JSON object from another object, overwriting existing keys + + Inserts all values from JSON object @a j and overwrites existing keys. + + @param[in] j JSON object to read values from + + @throw type_error.312 if called on JSON values other than objects; example: + `"cannot use update() with string"` + + @complexity O(N*log(size() + N)), where N is the number of elements to + insert. + + @liveexample{The example shows how `update()` is used.,update} + + @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update + + @since version 3.0.0 + */ + void update(const_reference j) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); + } + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); + } + + for (auto it = j.cbegin(); it != j.cend(); ++it) + { + m_value.object->operator[](it.key()) = it.value(); + } + } + + /*! + @brief updates a JSON object from another object, overwriting existing keys + + Inserts all values from from range `[first, last)` and overwrites existing + keys. + + @param[in] first begin of the range of elements to insert + @param[in] last end of the range of elements to insert + + @throw type_error.312 if called on JSON values other than objects; example: + `"cannot use update() with string"` + @throw invalid_iterator.202 if iterator @a first or @a last does does not + point to an object; example: `"iterators first and last must point to + objects"` + @throw invalid_iterator.210 if @a first and @a last do not belong to the + same JSON value; example: `"iterators do not fit"` + + @complexity O(N*log(size() + N)), where N is the number of elements to + insert. + + @liveexample{The example shows how `update()` is used__range.,update} + + @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update + + @since version 3.0.0 + */ + void update(const_iterator first, const_iterator last) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object() + || !last.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); + } + + for (auto it = first; it != last; ++it) + { + m_value.object->operator[](it.key()) = it.value(); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + assert_invariant(); + } + + /*! + @brief exchanges the values + + Exchanges the contents of the JSON value from @a left with those of @a right. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. implemented as a friend function callable via ADL. + + @param[in,out] left JSON value to exchange the contents with + @param[in,out] right JSON value to exchange the contents with + + @complexity Constant. + + @liveexample{The example below shows how JSON values can be swapped with + `swap()`.,swap__reference} + + @since version 1.0.0 + */ + friend void swap(reference left, reference right) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + left.swap(right); + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON array with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other array to exchange the contents with + + @throw type_error.310 when JSON value is not an array; example: `"cannot + use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how arrays can be swapped with + `swap()`.,swap__array_t} + + @since version 1.0.0 + */ + void swap(array_t& other) + { + // swap only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON object with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other object to exchange the contents with + + @throw type_error.310 when JSON value is not an object; example: + `"cannot use swap() with string"` + + @complexity Constant. + + @liveexample{The example below shows how objects can be swapped with + `swap()`.,swap__object_t} + + @since version 1.0.0 + */ + void swap(object_t& other) + { + // swap only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other string to exchange the contents with + + @throw type_error.310 when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__string_t} + + @since version 1.0.0 + */ + void swap(string_t& other) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_string())) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); + } + } + + /*! + @brief exchanges the values + + Exchanges the contents of a JSON string with those of @a other. Does not + invoke any move, copy, or swap operations on individual elements. All + iterators and references remain valid. The past-the-end iterator is + invalidated. + + @param[in,out] other binary to exchange the contents with + + @throw type_error.310 when JSON value is not a string; example: `"cannot + use swap() with boolean"` + + @complexity Constant. + + @liveexample{The example below shows how strings can be swapped with + `swap()`.,swap__binary_t} + + @since version 3.8.0 + */ + void swap(binary_t& other) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); + } + } + + /// @copydoc swap(binary_t) + void swap(typename binary_t::container_type& other) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /*! + @brief comparison: equal + + Compares two JSON values for equality according to the following rules: + - Two JSON values are equal if (1) they are from the same type and (2) + their stored values are the same according to their respective + `operator==`. + - Integer and floating-point numbers are automatically converted before + comparison. Note that two NaN values are always treated as unequal. + - Two JSON null values are equal. + + @note Floating-point inside JSON values numbers are compared with + `json::number_float_t::operator==` which is `double::operator==` by + default. To compare floating-point while respecting an epsilon, an alternative + [comparison function](https://github.com/mariokonrad/marnav/blob/master/include/marnav/math/floatingpoint.hpp#L34-#L39) + could be used, for instance + @code {.cpp} + template::value, T>::type> + inline bool is_same(T a, T b, T epsilon = std::numeric_limits::epsilon()) noexcept + { + return std::abs(a - b) <= epsilon; + } + @endcode + Or you can self-defined operator equal function like this: + @code {.cpp} + bool my_equal(const_reference lhs, const_reference rhs) { + const auto lhs_type lhs.type(); + const auto rhs_type rhs.type(); + if (lhs_type == rhs_type) { + switch(lhs_type) + // self_defined case + case value_t::number_float: + return std::abs(lhs - rhs) <= std::numeric_limits::epsilon(); + // other cases remain the same with the original + ... + } + ... + } + @endcode + + @note NaN values never compare equal to themselves or to other NaN values. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are equal + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @complexity Linear. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__equal} + + @since version 1.0.0 + */ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + return *lhs.m_value.array == *rhs.m_value.array; + + case value_t::object: + return *lhs.m_value.object == *rhs.m_value.object; + + case value_t::null: + return true; + + case value_t::string: + return *lhs.m_value.string == *rhs.m_value.string; + + case value_t::boolean: + return lhs.m_value.boolean == rhs.m_value.boolean; + + case value_t::number_integer: + return lhs.m_value.number_integer == rhs.m_value.number_integer; + + case value_t::number_unsigned: + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + + case value_t::number_float: + return lhs.m_value.number_float == rhs.m_value.number_float; + + case value_t::binary: + return *lhs.m_value.binary == *rhs.m_value.binary; + + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs == basic_json(rhs); + } + + /*! + @brief comparison: equal + @copydoc operator==(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) == rhs; + } + + /*! + @brief comparison: not equal + + Compares two JSON values for inequality by calculating `not (lhs == rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether the values @a lhs and @a rhs are not equal + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__notequal} + + @since version 1.0.0 + */ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs == rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs != basic_json(rhs); + } + + /*! + @brief comparison: not equal + @copydoc operator!=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) != rhs; + } + + /*! + @brief comparison: less than + + Compares whether one JSON value @a lhs is less than another JSON value @a + rhs according to the following rules: + - If @a lhs and @a rhs have the same type, the values are compared using + the default `<` operator. + - Integer and floating-point numbers are automatically converted before + comparison + - In case @a lhs and @a rhs have different types, the values are ignored + and the order of the types is considered, see + @ref operator<(const value_t, const value_t). + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__less} + + @since version 1.0.0 + */ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + // note parentheses are necessary, see + // https://github.com/nlohmann/json/issues/1530 + return (*lhs.m_value.array) < (*rhs.m_value.array); + + case value_t::object: + return (*lhs.m_value.object) < (*rhs.m_value.object); + + case value_t::null: + return false; + + case value_t::string: + return (*lhs.m_value.string) < (*rhs.m_value.string); + + case value_t::boolean: + return (lhs.m_value.boolean) < (rhs.m_value.boolean); + + case value_t::number_integer: + return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); + + case value_t::number_unsigned: + return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); + + case value_t::number_float: + return (lhs.m_value.number_float) < (rhs.m_value.number_float); + + case value_t::binary: + return (*lhs.m_value.binary) < (*rhs.m_value.binary); + + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); + } + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs < basic_json(rhs); + } + + /*! + @brief comparison: less than + @copydoc operator<(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) < rhs; + } + + /*! + @brief comparison: less than or equal + + Compares whether one JSON value @a lhs is less than or equal to another + JSON value by calculating `not (rhs < lhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is less than or equal to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greater} + + @since version 1.0.0 + */ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return !(rhs < lhs); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs <= basic_json(rhs); + } + + /*! + @brief comparison: less than or equal + @copydoc operator<=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) <= rhs; + } + + /*! + @brief comparison: greater than + + Compares whether one JSON value @a lhs is greater than another + JSON value by calculating `not (lhs <= rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__lessequal} + + @since version 1.0.0 + */ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs <= rhs); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs > basic_json(rhs); + } + + /*! + @brief comparison: greater than + @copydoc operator>(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) > rhs; + } + + /*! + @brief comparison: greater than or equal + + Compares whether one JSON value @a lhs is greater than or equal to another + JSON value by calculating `not (lhs < rhs)`. + + @param[in] lhs first JSON value to consider + @param[in] rhs second JSON value to consider + @return whether @a lhs is greater than or equal to @a rhs + + @complexity Linear. + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @liveexample{The example demonstrates comparing several JSON + types.,operator__greaterequal} + + @since version 1.0.0 + */ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs < rhs); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept + { + return lhs >= basic_json(rhs); + } + + /*! + @brief comparison: greater than or equal + @copydoc operator>=(const_reference, const_reference) + */ + template::value, int>::type = 0> + friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) >= rhs; + } + + /// @} + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ + + /*! + @brief serialize to stream + + Serialize the given JSON value @a j to the output stream @a o. The JSON + value will be serialized using the @ref dump member function. + + - The indentation of the output can be controlled with the member variable + `width` of the output stream @a o. For instance, using the manipulator + `std::setw(4)` on @a o sets the indentation level to `4` and the + serialization result is the same as calling `dump(4)`. + + - The indentation character can be controlled with the member variable + `fill` of the output stream @a o. For instance, the manipulator + `std::setfill('\\t')` sets indentation to use a tab character rather than + the default space character. + + @param[in,out] o stream to serialize to + @param[in] j JSON value to serialize + + @return the stream @a o + + @throw type_error.316 if a string stored inside the JSON value is not + UTF-8 encoded + + @complexity Linear. + + @liveexample{The example below shows the serialization with different + parameters to `width` to adjust the indentation level.,operator_serialize} + + @since version 1.0.0; indentation character added in version 3.0.0 + */ + friend std::ostream& operator<<(std::ostream& o, const basic_json& j) + { + // read width member and use it as indentation parameter if nonzero + const bool pretty_print = o.width() > 0; + const auto indentation = pretty_print ? o.width() : 0; + + // reset width to 0 for subsequent calls to this stream + o.width(0); + + // do the actual serialization + serializer s(detail::output_adapter(o), o.fill()); + s.dump(j, pretty_print, false, static_cast(indentation)); + return o; + } + + /*! + @brief serialize to stream + @deprecated This stream operator is deprecated and will be removed in + future 4.0.0 of the library. Please use + @ref operator<<(std::ostream&, const basic_json&) + instead; that is, replace calls like `j >> o;` with `o << j;`. + @since version 1.0.0; deprecated since version 3.0.0 + */ + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) + friend std::ostream& operator>>(const basic_json& j, std::ostream& o) + { + return o << j; + } + + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /*! + @brief deserialize from a compatible input + + @tparam InputType A compatible input, for instance + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the parser callback function + @a cb or reading from the input @a i has a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `parse()` function reading + from an array.,parse__array__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__string__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function with + and without callback function.,parse__istream__parser_callback_t} + + @liveexample{The example below demonstrates the `parse()` function reading + from a contiguous container.,parse__contiguouscontainer__parser_callback_t} + + @since version 2.0.3 (contiguous containers); version 3.9.0 allowed to + ignore comments. + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(InputType&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /*! + @brief deserialize from a pair of character iterators + + The value_type of the iterator must be a integral type with size of 1, 2 or + 4 bytes, which will be interpreted respectively as UTF-8, UTF-16 and UTF-32. + + @param[in] first iterator to start of character range + @param[in] last iterator to end of character range + @param[in] cb a parser callback function of type @ref parser_callback_t + which is used to control the deserialization by filtering unwanted values + (optional) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(IteratorType first, + IteratorType last, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) + static basic_json parse(detail::span_input_adapter&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /*! + @brief check if the input is valid JSON + + Unlike the @ref parse(InputType&&, const parser_callback_t,const bool) + function, this function neither throws an exception in case of invalid JSON + input (i.e., a parse error) nor creates diagnostic information. + + @tparam InputType A compatible input, for instance + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default) + + @return Whether the input read from @a i is valid JSON. + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `accept()` function reading + from a string.,accept__string} + */ + template + static bool accept(InputType&& i, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); + } + + template + static bool accept(IteratorType first, IteratorType last, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) + static bool accept(detail::span_input_adapter&& i, + const bool ignore_comments = false) + { + return parser(i.get(), nullptr, false, ignore_comments).accept(true); + } + + /*! + @brief generate SAX events + + The SAX event lister must follow the interface of @ref json_sax. + + This function reads from a compatible input. Examples are: + - an std::istream object + - a FILE pointer + - a C-style array of characters + - a pointer to a null-terminated string of single byte characters + - an object obj for which begin(obj) and end(obj) produces a valid pair of + iterators. + + @param[in] i input to read from + @param[in,out] sax SAX event listener + @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON) + @param[in] strict whether the input has to be consumed completely + @param[in] ignore_comments whether comments should be ignored and treated + like whitespace (true) or yield a parse error (true); (optional, false by + default); only applies to the JSON file format. + + @return return value of the last processed SAX event + + @throw parse_error.101 if a parse error occurs; example: `""unexpected end + of input; expected string literal""` + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. The complexity can be higher if the SAX consumer @a sax has + a super-linear complexity. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below demonstrates the `sax_parse()` function + reading from string and processing the events with a user-defined SAX + event consumer.,sax_parse} + + @since version 3.2.0 + */ + template + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(InputType&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::forward(i)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + template + JSON_HEDLEY_NON_NULL(3) + static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::move(first), std::move(last)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + template + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = i.get(); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /*! + @brief deserialize from stream + @deprecated This stream operator is deprecated and will be removed in + version 4.0.0 of the library. Please use + @ref operator>>(std::istream&, basic_json&) + instead; that is, replace calls like `j << i;` with `i >> j;`. + @since version 1.0.0; deprecated since version 3.0.0 + */ + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) + friend std::istream& operator<<(basic_json& j, std::istream& i) + { + return operator>>(i, j); + } + + /*! + @brief deserialize from stream + + Deserializes an input stream to a JSON value. + + @param[in,out] i input stream to read a serialized JSON value from + @param[in,out] j JSON value to write the deserialized input to + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + + @complexity Linear in the length of the input. The parser is a predictive + LL(1) parser. + + @note A UTF-8 byte order mark is silently ignored. + + @liveexample{The example below shows how a JSON value is constructed by + reading a serialization from a stream.,operator_deserialize} + + @sa parse(std::istream&, const parser_callback_t) for a variant with a + parser callback function to filter values while parsing + + @since version 1.0.0 + */ + friend std::istream& operator>>(std::istream& i, basic_json& j) + { + parser(detail::input_adapter(i)).parse(false, j); + return i; + } + + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /*! + @brief return the type as string + + Returns the type name as string to be used in error messages - usually to + indicate that a function was called on a wrong JSON type. + + @return a string representation of a the @a m_type member: + Value type | return value + ----------- | ------------- + null | `"null"` + boolean | `"boolean"` + string | `"string"` + number | `"number"` (for all number types) + object | `"object"` + array | `"array"` + binary | `"binary"` + discarded | `"discarded"` + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + + @complexity Constant. + + @liveexample{The following code exemplifies `type_name()` for all JSON + types.,type_name} + + @sa @ref type() -- return the type of the JSON value + @sa @ref operator value_t() -- return the type of the JSON value (implicit) + + @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` + since 3.0.0 + */ + JSON_HEDLEY_RETURNS_NON_NULL + const char* type_name() const noexcept + { + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::binary: + return "binary"; + case value_t::discarded: + return "discarded"; + default: + return "number"; + } + } + } + + + private: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + public: + /*! + @brief create a CBOR serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the CBOR (Concise + Binary Object Representation) serialization format. CBOR is a binary + serialization format which aims to be more compact than JSON itself, yet + more efficient to parse. + + The library uses the following mapping from JSON values types to + CBOR types according to the CBOR specification (RFC 7049): + + JSON value type | value/range | CBOR type | first byte + --------------- | ------------------------------------------ | ---------------------------------- | --------------- + null | `null` | Null | 0xF6 + boolean | `true` | True | 0xF5 + boolean | `false` | False | 0xF4 + number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B + number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A + number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 + number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 + number_integer | -24..-1 | Negative integer | 0x20..0x37 + number_integer | 0..23 | Integer | 0x00..0x17 + number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A + number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B + number_unsigned | 0..23 | Integer | 0x00..0x17 + number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 + number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 + number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A + number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B + number_float | *any value representable by a float* | Single-Precision Float | 0xFA + number_float | *any value NOT representable by a float* | Double-Precision Float | 0xFB + string | *length*: 0..23 | UTF-8 string | 0x60..0x77 + string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 + string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 + string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A + string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B + array | *size*: 0..23 | array | 0x80..0x97 + array | *size*: 23..255 | array (1 byte follow) | 0x98 + array | *size*: 256..65535 | array (2 bytes follow) | 0x99 + array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A + array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B + object | *size*: 0..23 | map | 0xA0..0xB7 + object | *size*: 23..255 | map (1 byte follow) | 0xB8 + object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 + object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA + object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB + binary | *size*: 0..23 | byte string | 0x40..0x57 + binary | *size*: 23..255 | byte string (1 byte follow) | 0x58 + binary | *size*: 256..65535 | byte string (2 bytes follow) | 0x59 + binary | *size*: 65536..4294967295 | byte string (4 bytes follow) | 0x5A + binary | *size*: 4294967296..18446744073709551615 | byte string (8 bytes follow) | 0x5B + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a CBOR value. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @note The following CBOR types are not used in the conversion: + - UTF-8 strings terminated by "break" (0x7F) + - arrays terminated by "break" (0x9F) + - maps terminated by "break" (0xBF) + - byte strings terminated by "break" (0x5F) + - date/time (0xC0..0xC1) + - bignum (0xC2..0xC3) + - decimal fraction (0xC4) + - bigfloat (0xC5) + - expected conversions (0xD5..0xD7) + - simple values (0xE0..0xF3, 0xF8) + - undefined (0xF7) + - half-precision floats (0xF9) + - break (0xFF) + + @param[in] j JSON value to serialize + @return CBOR serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in CBOR format.,to_cbor} + + @sa http://cbor.io + @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the + analogous deserialization + @sa @ref to_msgpack(const basic_json&) for the related MessagePack format + @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9; compact representation of floating-point numbers + since version 3.8.0 + */ + static std::vector to_cbor(const basic_json& j) + { + std::vector result; + to_cbor(j, result); + return result; + } + + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /*! + @brief create a MessagePack serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the MessagePack + serialization format. MessagePack is a binary serialization format which + aims to be more compact than JSON itself, yet more efficient to parse. + + The library uses the following mapping from JSON values types to + MessagePack types according to the MessagePack specification: + + JSON value type | value/range | MessagePack type | first byte + --------------- | --------------------------------- | ---------------- | ---------- + null | `null` | nil | 0xC0 + boolean | `true` | true | 0xC3 + boolean | `false` | false | 0xC2 + number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 + number_integer | -2147483648..-32769 | int32 | 0xD2 + number_integer | -32768..-129 | int16 | 0xD1 + number_integer | -128..-33 | int8 | 0xD0 + number_integer | -32..-1 | negative fixint | 0xE0..0xFF + number_integer | 0..127 | positive fixint | 0x00..0x7F + number_integer | 128..255 | uint 8 | 0xCC + number_integer | 256..65535 | uint 16 | 0xCD + number_integer | 65536..4294967295 | uint 32 | 0xCE + number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF + number_unsigned | 0..127 | positive fixint | 0x00..0x7F + number_unsigned | 128..255 | uint 8 | 0xCC + number_unsigned | 256..65535 | uint 16 | 0xCD + number_unsigned | 65536..4294967295 | uint 32 | 0xCE + number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF + number_float | *any value representable by a float* | float 32 | 0xCA + number_float | *any value NOT representable by a float* | float 64 | 0xCB + string | *length*: 0..31 | fixstr | 0xA0..0xBF + string | *length*: 32..255 | str 8 | 0xD9 + string | *length*: 256..65535 | str 16 | 0xDA + string | *length*: 65536..4294967295 | str 32 | 0xDB + array | *size*: 0..15 | fixarray | 0x90..0x9F + array | *size*: 16..65535 | array 16 | 0xDC + array | *size*: 65536..4294967295 | array 32 | 0xDD + object | *size*: 0..15 | fix map | 0x80..0x8F + object | *size*: 16..65535 | map 16 | 0xDE + object | *size*: 65536..4294967295 | map 32 | 0xDF + binary | *size*: 0..255 | bin 8 | 0xC4 + binary | *size*: 256..65535 | bin 16 | 0xC5 + binary | *size*: 65536..4294967295 | bin 32 | 0xC6 + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a MessagePack value. + + @note The following values can **not** be converted to a MessagePack value: + - strings with more than 4294967295 bytes + - byte strings with more than 4294967295 bytes + - arrays with more than 4294967295 elements + - objects with more than 4294967295 elements + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @param[in] j JSON value to serialize + @return MessagePack serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in MessagePack format.,to_msgpack} + + @sa http://msgpack.org + @sa @ref from_msgpack for the analogous deserialization + @sa @ref to_cbor(const basic_json& for the related CBOR format + @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9 + */ + static std::vector to_msgpack(const basic_json& j) + { + std::vector result; + to_msgpack(j, result); + return result; + } + + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /*! + @brief create a UBJSON serialization of a given JSON value + + Serializes a given JSON value @a j to a byte vector using the UBJSON + (Universal Binary JSON) serialization format. UBJSON aims to be more compact + than JSON itself, yet more efficient to parse. + + The library uses the following mapping from JSON values types to + UBJSON types according to the UBJSON specification: + + JSON value type | value/range | UBJSON type | marker + --------------- | --------------------------------- | ----------- | ------ + null | `null` | null | `Z` + boolean | `true` | true | `T` + boolean | `false` | false | `F` + number_integer | -9223372036854775808..-2147483649 | int64 | `L` + number_integer | -2147483648..-32769 | int32 | `l` + number_integer | -32768..-129 | int16 | `I` + number_integer | -128..127 | int8 | `i` + number_integer | 128..255 | uint8 | `U` + number_integer | 256..32767 | int16 | `I` + number_integer | 32768..2147483647 | int32 | `l` + number_integer | 2147483648..9223372036854775807 | int64 | `L` + number_unsigned | 0..127 | int8 | `i` + number_unsigned | 128..255 | uint8 | `U` + number_unsigned | 256..32767 | int16 | `I` + number_unsigned | 32768..2147483647 | int32 | `l` + number_unsigned | 2147483648..9223372036854775807 | int64 | `L` + number_unsigned | 2147483649..18446744073709551615 | high-precision | `H` + number_float | *any value* | float64 | `D` + string | *with shortest length indicator* | string | `S` + array | *see notes on optimized format* | array | `[` + object | *see notes on optimized format* | map | `{` + + @note The mapping is **complete** in the sense that any JSON value type + can be converted to a UBJSON value. + + @note The following values can **not** be converted to a UBJSON value: + - strings with more than 9223372036854775807 bytes (theoretical) + + @note The following markers are not used in the conversion: + - `Z`: no-op values are not created. + - `C`: single-byte strings are serialized with `S` markers. + + @note Any UBJSON output created @ref to_ubjson can be successfully parsed + by @ref from_ubjson. + + @note If NaN or Infinity are stored inside a JSON number, they are + serialized properly. This behavior differs from the @ref dump() + function which serializes NaN or Infinity to `null`. + + @note The optimized formats for containers are supported: Parameter + @a use_size adds size information to the beginning of a container and + removes the closing marker. Parameter @a use_type further checks + whether all elements of a container have the same type and adds the + type marker to the beginning of the container. The @a use_type + parameter must only be used together with @a use_size = true. Note + that @a use_size = true alone may result in larger representations - + the benefit of this parameter is that the receiving side is + immediately informed on the number of elements of the container. + + @note If the JSON data contains the binary type, the value stored is a list + of integers, as suggested by the UBJSON documentation. In particular, + this means that serialization and the deserialization of a JSON + containing binary values into UBJSON and back will result in a + different JSON object. + + @param[in] j JSON value to serialize + @param[in] use_size whether to add size annotations to container types + @param[in] use_type whether to add type annotations to container types + (must be combined with @a use_size = true) + @return UBJSON serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in UBJSON format.,to_ubjson} + + @sa http://ubjson.org + @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the + analogous deserialization + @sa @ref to_cbor(const basic_json& for the related CBOR format + @sa @ref to_msgpack(const basic_json&) for the related MessagePack format + + @since version 3.1.0 + */ + static std::vector to_ubjson(const basic_json& j, + const bool use_size = false, + const bool use_type = false) + { + std::vector result; + to_ubjson(j, result, use_size, use_type); + return result; + } + + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + + /*! + @brief Serializes the given JSON object `j` to BSON and returns a vector + containing the corresponding BSON-representation. + + BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are + stored as a single entity (a so-called document). + + The library uses the following mapping from JSON values types to BSON types: + + JSON value type | value/range | BSON type | marker + --------------- | --------------------------------- | ----------- | ------ + null | `null` | null | 0x0A + boolean | `true`, `false` | boolean | 0x08 + number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 + number_integer | -2147483648..2147483647 | int32 | 0x10 + number_integer | 2147483648..9223372036854775807 | int64 | 0x12 + number_unsigned | 0..2147483647 | int32 | 0x10 + number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 + number_unsigned | 9223372036854775808..18446744073709551615| -- | -- + number_float | *any value* | double | 0x01 + string | *any value* | string | 0x02 + array | *any value* | document | 0x04 + object | *any value* | document | 0x03 + binary | *any value* | binary | 0x05 + + @warning The mapping is **incomplete**, since only JSON-objects (and things + contained therein) can be serialized to BSON. + Also, integers larger than 9223372036854775807 cannot be serialized to BSON, + and the keys may not contain U+0000, since they are serialized a + zero-terminated c-strings. + + @throw out_of_range.407 if `j.is_number_unsigned() && j.get() > 9223372036854775807` + @throw out_of_range.409 if a key in `j` contains a NULL (U+0000) + @throw type_error.317 if `!j.is_object()` + + @pre The input `j` is required to be an object: `j.is_object() == true`. + + @note Any BSON output created via @ref to_bson can be successfully parsed + by @ref from_bson. + + @param[in] j JSON value to serialize + @return BSON serialization as byte vector + + @complexity Linear in the size of the JSON value @a j. + + @liveexample{The example shows the serialization of a JSON value to a byte + vector in BSON format.,to_bson} + + @sa http://bsonspec.org/spec.html + @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the + analogous deserialization + @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the + related UBJSON format + @sa @ref to_cbor(const basic_json&) for the related CBOR format + @sa @ref to_msgpack(const basic_json&) for the related MessagePack format + */ + static std::vector to_bson(const basic_json& j) + { + std::vector result; + to_bson(j, result); + return result; + } + + /*! + @brief Serializes the given JSON object `j` to BSON and forwards the + corresponding BSON-representation to the given output_adapter `o`. + @param j The JSON object to convert to BSON. + @param o The output adapter that receives the binary BSON representation. + @pre The input `j` shall be an object: `j.is_object() == true` + @sa @ref to_bson(const basic_json&) + */ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /*! + @copydoc to_bson(const basic_json&, detail::output_adapter) + */ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + + /*! + @brief create a JSON value from an input in CBOR format + + Deserializes a given input @a i to a JSON value using the CBOR (Concise + Binary Object Representation) serialization format. + + The library maps CBOR types to JSON value types as follows: + + CBOR type | JSON value type | first byte + ---------------------- | --------------- | ---------- + Integer | number_unsigned | 0x00..0x17 + Unsigned integer | number_unsigned | 0x18 + Unsigned integer | number_unsigned | 0x19 + Unsigned integer | number_unsigned | 0x1A + Unsigned integer | number_unsigned | 0x1B + Negative integer | number_integer | 0x20..0x37 + Negative integer | number_integer | 0x38 + Negative integer | number_integer | 0x39 + Negative integer | number_integer | 0x3A + Negative integer | number_integer | 0x3B + Byte string | binary | 0x40..0x57 + Byte string | binary | 0x58 + Byte string | binary | 0x59 + Byte string | binary | 0x5A + Byte string | binary | 0x5B + UTF-8 string | string | 0x60..0x77 + UTF-8 string | string | 0x78 + UTF-8 string | string | 0x79 + UTF-8 string | string | 0x7A + UTF-8 string | string | 0x7B + UTF-8 string | string | 0x7F + array | array | 0x80..0x97 + array | array | 0x98 + array | array | 0x99 + array | array | 0x9A + array | array | 0x9B + array | array | 0x9F + map | object | 0xA0..0xB7 + map | object | 0xB8 + map | object | 0xB9 + map | object | 0xBA + map | object | 0xBB + map | object | 0xBF + False | `false` | 0xF4 + True | `true` | 0xF5 + Null | `null` | 0xF6 + Half-Precision Float | number_float | 0xF9 + Single-Precision Float | number_float | 0xFA + Double-Precision Float | number_float | 0xFB + + @warning The mapping is **incomplete** in the sense that not all CBOR + types can be converted to a JSON value. The following CBOR types + are not supported and will yield parse errors (parse_error.112): + - date/time (0xC0..0xC1) + - bignum (0xC2..0xC3) + - decimal fraction (0xC4) + - bigfloat (0xC5) + - expected conversions (0xD5..0xD7) + - simple values (0xE0..0xF3, 0xF8) + - undefined (0xF7) + + @warning CBOR allows map keys of any type, whereas JSON only allows + strings as keys in object values. Therefore, CBOR maps with keys + other than UTF-8 strings are rejected (parse_error.113). + + @note Any CBOR output created @ref to_cbor can be successfully parsed by + @ref from_cbor. + + @param[in] i an input in CBOR format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + @param[in] tag_handler how to treat CBOR tags (optional, error by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if unsupported features from CBOR were + used in the given input @a v or if the input is not valid CBOR + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in CBOR + format to a JSON value.,from_cbor} + + @sa http://cbor.io + @sa @ref to_cbor(const basic_json&) for the analogous serialization + @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the + related MessagePack format + @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the + related UBJSON format + + @since version 2.0.9; parameter @a start_index since 2.1.1; changed to + consume input adapters, removed start_index parameter, and added + @a strict parameter since 3.0.0; added @a allow_exceptions parameter + since 3.2.0; added @a tag_handler parameter since 3.9.0. + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); + } + + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @brief create a JSON value from an input in MessagePack format + + Deserializes a given input @a i to a JSON value using the MessagePack + serialization format. + + The library maps MessagePack types to JSON value types as follows: + + MessagePack type | JSON value type | first byte + ---------------- | --------------- | ---------- + positive fixint | number_unsigned | 0x00..0x7F + fixmap | object | 0x80..0x8F + fixarray | array | 0x90..0x9F + fixstr | string | 0xA0..0xBF + nil | `null` | 0xC0 + false | `false` | 0xC2 + true | `true` | 0xC3 + float 32 | number_float | 0xCA + float 64 | number_float | 0xCB + uint 8 | number_unsigned | 0xCC + uint 16 | number_unsigned | 0xCD + uint 32 | number_unsigned | 0xCE + uint 64 | number_unsigned | 0xCF + int 8 | number_integer | 0xD0 + int 16 | number_integer | 0xD1 + int 32 | number_integer | 0xD2 + int 64 | number_integer | 0xD3 + str 8 | string | 0xD9 + str 16 | string | 0xDA + str 32 | string | 0xDB + array 16 | array | 0xDC + array 32 | array | 0xDD + map 16 | object | 0xDE + map 32 | object | 0xDF + bin 8 | binary | 0xC4 + bin 16 | binary | 0xC5 + bin 32 | binary | 0xC6 + ext 8 | binary | 0xC7 + ext 16 | binary | 0xC8 + ext 32 | binary | 0xC9 + fixext 1 | binary | 0xD4 + fixext 2 | binary | 0xD5 + fixext 4 | binary | 0xD6 + fixext 8 | binary | 0xD7 + fixext 16 | binary | 0xD8 + negative fixint | number_integer | 0xE0-0xFF + + @note Any MessagePack output created @ref to_msgpack can be successfully + parsed by @ref from_msgpack. + + @param[in] i an input in MessagePack format convertible to an input + adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if unsupported features from MessagePack were + used in the given input @a i or if the input is not valid MessagePack + @throw parse_error.113 if a string was expected as map key, but not found + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + MessagePack format to a JSON value.,from_msgpack} + + @sa http://msgpack.org + @sa @ref to_msgpack(const basic_json&) for the analogous serialization + @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for + the related UBJSON format + @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for + the related BSON format + + @since version 2.0.9; parameter @a start_index since 2.1.1; changed to + consume input adapters, removed start_index parameter, and added + @a strict parameter since 3.0.0; added @a allow_exceptions parameter + since 3.2.0 + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_msgpack(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + /*! + @brief create a JSON value from an input in UBJSON format + + Deserializes a given input @a i to a JSON value using the UBJSON (Universal + Binary JSON) serialization format. + + The library maps UBJSON types to JSON value types as follows: + + UBJSON type | JSON value type | marker + ----------- | --------------------------------------- | ------ + no-op | *no value, next value is read* | `N` + null | `null` | `Z` + false | `false` | `F` + true | `true` | `T` + float32 | number_float | `d` + float64 | number_float | `D` + uint8 | number_unsigned | `U` + int8 | number_integer | `i` + int16 | number_integer | `I` + int32 | number_integer | `l` + int64 | number_integer | `L` + high-precision number | number_integer, number_unsigned, or number_float - depends on number string | 'H' + string | string | `S` + char | string | `C` + array | array (optimized values are supported) | `[` + object | object (optimized values are supported) | `{` + + @note The mapping is **complete** in the sense that any UBJSON value can + be converted to a JSON value. + + @param[in] i an input in UBJSON format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.110 if the given input ends prematurely or the end of + file was not reached when @a strict was set to true + @throw parse_error.112 if a parse error occurs + @throw parse_error.113 if a string could not be parsed successfully + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + UBJSON format to a JSON value.,from_ubjson} + + @sa http://ubjson.org + @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the + analogous serialization + @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for + the related MessagePack format + @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for + the related BSON format + + @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0 + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_ubjson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + + /*! + @brief Create a JSON value from an input in BSON format + + Deserializes a given input @a i to a JSON value using the BSON (Binary JSON) + serialization format. + + The library maps BSON record types to JSON value types as follows: + + BSON type | BSON marker byte | JSON value type + --------------- | ---------------- | --------------------------- + double | 0x01 | number_float + string | 0x02 | string + document | 0x03 | object + array | 0x04 | array + binary | 0x05 | still unsupported + undefined | 0x06 | still unsupported + ObjectId | 0x07 | still unsupported + boolean | 0x08 | boolean + UTC Date-Time | 0x09 | still unsupported + null | 0x0A | null + Regular Expr. | 0x0B | still unsupported + DB Pointer | 0x0C | still unsupported + JavaScript Code | 0x0D | still unsupported + Symbol | 0x0E | still unsupported + JavaScript Code | 0x0F | still unsupported + int32 | 0x10 | number_integer + Timestamp | 0x11 | still unsupported + 128-bit decimal float | 0x13 | still unsupported + Max Key | 0x7F | still unsupported + Min Key | 0xFF | still unsupported + + @warning The mapping is **incomplete**. The unsupported mappings + are indicated in the table above. + + @param[in] i an input in BSON format convertible to an input adapter + @param[in] strict whether to expect the input to be consumed until EOF + (true by default) + @param[in] allow_exceptions whether to throw exceptions in case of a + parse error (optional, true by default) + + @return deserialized JSON value; in case of a parse error and + @a allow_exceptions set to `false`, the return value will be + value_t::discarded. + + @throw parse_error.114 if an unsupported BSON record type is encountered + + @complexity Linear in the size of the input @a i. + + @liveexample{The example shows the deserialization of a byte vector in + BSON format to a JSON value.,from_bson} + + @sa http://bsonspec.org/spec.html + @sa @ref to_bson(const basic_json&) for the analogous serialization + @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool, const cbor_tag_handler_t) for the + related CBOR format + @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for + the related MessagePack format + @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the + related UBJSON format + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /*! + @copydoc from_bson(detail::input_adapter&&, const bool, const bool) + */ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_bson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + /// @} + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. Similar to @ref operator[](const typename + object_t::key_type&), `null` values are created in arrays and objects if + necessary. + + In particular: + - If the JSON pointer points to an object key that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. + - If the JSON pointer points to an array index that does not exist, it + is created an filled with a `null` value before a reference to it + is returned. All indices between the current maximum and the given + index are also filled with `null`. + - The special value `-` is treated as a synonym for the index past the + end. + + @param[in] ptr a JSON pointer + + @return reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer} + + @since version 2.0.0 + */ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Uses a JSON pointer to retrieve a reference to the respective JSON value. + No bound checking is performed. The function does not change the JSON + value; no `null` values are created. In particular, the special value + `-` yields an exception. + + @param[in] ptr JSON pointer to the desired element + + @return const reference to the element pointed to by @a ptr + + @complexity Constant. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + + @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} + + @since version 2.0.0 + */ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a reference to the element at with specified JSON pointer @a ptr, + with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.403 if the JSON pointer describes a key of an object + which cannot be found. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer} + */ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /*! + @brief access specified element via JSON Pointer + + Returns a const reference to the element at with specified JSON pointer @a + ptr, with bounds checking. + + @param[in] ptr JSON pointer to the desired element + + @return reference to the element pointed to by @a ptr + + @throw parse_error.106 if an array index in the passed JSON pointer @a ptr + begins with '0'. See example below. + + @throw parse_error.109 if an array index in the passed JSON pointer @a ptr + is not a number. See example below. + + @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr + is out of range. See example below. + + @throw out_of_range.402 if the array index '-' is used in the passed JSON + pointer @a ptr. As `at` provides checked access (and no elements are + implicitly inserted), the index '-' is always invalid. See example below. + + @throw out_of_range.403 if the JSON pointer describes a key of an object + which cannot be found. See example below. + + @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. + See example below. + + @exceptionsafety Strong guarantee: if an exception is thrown, there are no + changes in the JSON value. + + @complexity Constant. + + @since version 2.0.0 + + @liveexample{The behavior is shown in the example.,at_json_pointer_const} + */ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /*! + @brief return flattened JSON value + + The function creates a JSON object whose keys are JSON pointers (see [RFC + 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all + primitive. The original JSON value can be restored using the @ref + unflatten() function. + + @return an object that maps JSON pointers to primitive values + + @note Empty objects and arrays are flattened to `null` and will not be + reconstructed correctly by the @ref unflatten() function. + + @complexity Linear in the size the JSON value. + + @liveexample{The following code shows how a JSON object is flattened to an + object whose keys consist of JSON pointers.,flatten} + + @sa @ref unflatten() for the reverse function + + @since version 2.0.0 + */ + basic_json flatten() const + { + basic_json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /*! + @brief unflatten a previously flattened JSON value + + The function restores the arbitrary nesting of a JSON value that has been + flattened before using the @ref flatten() function. The JSON value must + meet certain constraints: + 1. The value must be an object. + 2. The keys must be JSON pointers (see + [RFC 6901](https://tools.ietf.org/html/rfc6901)) + 3. The mapped values must be primitive JSON types. + + @return the original JSON from a flattened version + + @note Empty objects and arrays are flattened by @ref flatten() to `null` + values and can not unflattened to their original type. Apart from + this example, for a JSON value `j`, the following is always true: + `j == j.flatten().unflatten()`. + + @complexity Linear in the size the JSON value. + + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + + @liveexample{The following code shows how a flattened JSON object is + unflattened into the original nested JSON object.,unflatten} + + @sa @ref flatten() for the reverse function + + @since version 2.0.0 + */ + basic_json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} + + ////////////////////////// + // JSON Patch functions // + ////////////////////////// + + /// @name JSON Patch functions + /// @{ + + /*! + @brief applies a JSON patch + + [JSON Patch](http://jsonpatch.com) defines a JSON document structure for + expressing a sequence of operations to apply to a JSON) document. With + this function, a JSON Patch is applied to the current JSON value by + executing all operations from the patch. + + @param[in] json_patch JSON patch document + @return patched document + + @note The application of a patch is atomic: Either all operations succeed + and the patched document is returned or an exception is thrown. In + any case, the original value is not changed: the patch is applied + to a copy of the value. + + @throw parse_error.104 if the JSON patch does not consist of an array of + objects + + @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory + attributes are missing); example: `"operation add must have member path"` + + @throw out_of_range.401 if an array index is out of range. + + @throw out_of_range.403 if a JSON pointer inside the patch could not be + resolved successfully in the current JSON value; example: `"key baz not + found"` + + @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", + "move") + + @throw other_error.501 if "test" operation was unsuccessful + + @complexity Linear in the size of the JSON value and the length of the + JSON patch. As usually only a fraction of the JSON value is affected by + the patch, the complexity can usually be neglected. + + @liveexample{The following code shows how a JSON patch is applied to a + value.,patch} + + @sa @ref diff -- create a JSON patch by comparing two JSON values + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) + + @since version 2.0.0 + */ + basic_json patch(const basic_json& json_patch) const + { + // make a working copy to apply the patch to + basic_json result = *this; + + // the valid JSON Patch operations + enum class patch_operations {add, remove, replace, move, copy, test, invalid}; + + const auto get_op = [](const std::string & op) + { + if (op == "add") + { + return patch_operations::add; + } + if (op == "remove") + { + return patch_operations::remove; + } + if (op == "replace") + { + return patch_operations::replace; + } + if (op == "move") + { + return patch_operations::move; + } + if (op == "copy") + { + return patch_operations::copy; + } + if (op == "test") + { + return patch_operations::test; + } + + return patch_operations::invalid; + }; + + // wrapper for "add" operation; add value at ptr + const auto operation_add = [&result](json_pointer & ptr, basic_json val) + { + // adding to the root of the target document means replacing it + if (ptr.empty()) + { + result = val; + return; + } + + // make sure the top element of the pointer exists + json_pointer top_pointer = ptr.top(); + if (top_pointer != ptr) + { + result.at(top_pointer); + } + + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result[ptr]; + + switch (parent.m_type) + { + case value_t::null: + case value_t::object: + { + // use operator[] to add value + parent[last_path] = val; + break; + } + + case value_t::array: + { + if (last_path == "-") + { + // special case: append to back + parent.push_back(val); + } + else + { + const auto idx = json_pointer::array_index(last_path); + if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) + { + // avoid undefined behavior + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); + } + + // default case: insert add offset + parent.insert(parent.begin() + static_cast(idx), val); + } + break; + } + + // if there exists a parent it cannot be primitive + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // LCOV_EXCL_LINE + } + }; + + // wrapper for "remove" operation; remove value at ptr + const auto operation_remove = [&result](json_pointer & ptr) + { + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result.at(ptr); + + // remove child + if (parent.is_object()) + { + // perform range check + auto it = parent.find(last_path); + if (JSON_HEDLEY_LIKELY(it != parent.end())) + { + parent.erase(it); + } + else + { + JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); + } + } + else if (parent.is_array()) + { + // note erase performs range check + parent.erase(json_pointer::array_index(last_path)); + } + }; + + // type check: top level value must be an array + if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); + } + + // iterate and apply the operations + for (const auto& val : json_patch) + { + // wrapper to get a value for an operation + const auto get_value = [&val](const std::string & op, + const std::string & member, + bool string_type) -> basic_json & + { + // find value + auto it = val.m_value.object->find(member); + + // context-sensitive error message + const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; + + // check if desired value is present + if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) + { + JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); + } + + // check if result is of type string + if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) + { + JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); + } + + // no error: return value + return it->second; + }; + + // type check: every element of the array must be an object + if (JSON_HEDLEY_UNLIKELY(!val.is_object())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); + } + + // collect mandatory members + const auto op = get_value("op", "op", true).template get(); + const auto path = get_value(op, "path", true).template get(); + json_pointer ptr(path); + + switch (get_op(op)) + { + case patch_operations::add: + { + operation_add(ptr, get_value("add", "value", false)); + break; + } + + case patch_operations::remove: + { + operation_remove(ptr); + break; + } + + case patch_operations::replace: + { + // the "path" location must exist - use at() + result.at(ptr) = get_value("replace", "value", false); + break; + } + + case patch_operations::move: + { + const auto from_path = get_value("move", "from", true).template get(); + json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The move operation is functionally identical to a + // "remove" operation on the "from" location, followed + // immediately by an "add" operation at the target + // location with the value that was just removed. + operation_remove(from_ptr); + operation_add(ptr, v); + break; + } + + case patch_operations::copy: + { + const auto from_path = get_value("copy", "from", true).template get(); + const json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The copy is functionally identical to an "add" + // operation at the target location using the value + // specified in the "from" member. + operation_add(ptr, v); + break; + } + + case patch_operations::test: + { + bool success = false; + JSON_TRY + { + // check if "value" matches the one at "path" + // the "path" location must exist - use at() + success = (result.at(ptr) == get_value("test", "value", false)); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + // ignore out of range errors: success remains false + } + + // throw an exception if test fails + if (JSON_HEDLEY_UNLIKELY(!success)) + { + JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); + } + + break; + } + + default: + { + // op must be "add", "remove", "replace", "move", "copy", or + // "test" + JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); + } + } + } + + return result; + } + + /*! + @brief creates a diff as a JSON patch + + Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can + be changed into the value @a target by calling @ref patch function. + + @invariant For two JSON values @a source and @a target, the following code + yields always `true`: + @code {.cpp} + source.patch(diff(source, target)) == target; + @endcode + + @note Currently, only `remove`, `add`, and `replace` operations are + generated. + + @param[in] source JSON value to compare from + @param[in] target JSON value to compare against + @param[in] path helper value to create JSON pointers + + @return a JSON patch to convert the @a source to @a target + + @complexity Linear in the lengths of @a source and @a target. + + @liveexample{The following code shows how a JSON patch is created as a + diff for two JSON values.,diff} + + @sa @ref patch -- apply a JSON patch + @sa @ref merge_patch -- apply a JSON Merge Patch + + @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) + + @since version 2.0.0 + */ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json diff(const basic_json& source, const basic_json& target, + const std::string& path = "") + { + // the patch + basic_json result(value_t::array); + + // if the values are the same, return empty patch + if (source == target) + { + return result; + } + + if (source.type() != target.type()) + { + // different types: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + return result; + } + + switch (source.type()) + { + case value_t::array: + { + // first pass: traverse common elements + std::size_t i = 0; + while (i < source.size() && i < target.size()) + { + // recursive call to compare array values at index i + auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + ++i; + } + + // i now reached the end of at least one array + // in a second pass, traverse the remaining elements + + // remove my remaining elements + const auto end_index = static_cast(result.size()); + while (i < source.size()) + { + // add operations in reverse order to avoid invalid + // indices + result.insert(result.begin() + end_index, object( + { + {"op", "remove"}, + {"path", path + "/" + std::to_string(i)} + })); + ++i; + } + + // add other remaining elements + while (i < target.size()) + { + result.push_back( + { + {"op", "add"}, + {"path", path + "/-"}, + {"value", target[i]} + }); + ++i; + } + + break; + } + + case value_t::object: + { + // first pass: traverse this object's elements + for (auto it = source.cbegin(); it != source.cend(); ++it) + { + // escape the key name to be used in a JSON patch + const auto key = json_pointer::escape(it.key()); + + if (target.find(it.key()) != target.end()) + { + // recursive call to compare object values at key it + auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + } + else + { + // found a key that is not in o -> remove it + result.push_back(object( + { + {"op", "remove"}, {"path", path + "/" + key} + })); + } + } + + // second pass: traverse other object's elements + for (auto it = target.cbegin(); it != target.cend(); ++it) + { + if (source.find(it.key()) == source.end()) + { + // found a key that is not in this -> add it + const auto key = json_pointer::escape(it.key()); + result.push_back( + { + {"op", "add"}, {"path", path + "/" + key}, + {"value", it.value()} + }); + } + } + + break; + } + + default: + { + // both primitive type: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + break; + } + } + + return result; + } + + /// @} + + //////////////////////////////// + // JSON Merge Patch functions // + //////////////////////////////// + + /// @name JSON Merge Patch functions + /// @{ + + /*! + @brief applies a JSON Merge Patch + + The merge patch format is primarily intended for use with the HTTP PATCH + method as a means of describing a set of modifications to a target + resource's content. This function applies a merge patch to the current + JSON value. + + The function implements the following algorithm from Section 2 of + [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): + + ``` + define MergePatch(Target, Patch): + if Patch is an Object: + if Target is not an Object: + Target = {} // Ignore the contents and set it to an empty Object + for each Name/Value pair in Patch: + if Value is null: + if Name exists in Target: + remove the Name/Value pair from Target + else: + Target[Name] = MergePatch(Target[Name], Value) + return Target + else: + return Patch + ``` + + Thereby, `Target` is the current object; that is, the patch is applied to + the current value. + + @param[in] apply_patch the patch to apply + + @complexity Linear in the lengths of @a patch. + + @liveexample{The following code shows how a JSON Merge Patch is applied to + a JSON document.,merge_patch} + + @sa @ref patch -- apply a JSON patch + @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) + + @since version 3.0.0 + */ + void merge_patch(const basic_json& apply_patch) + { + if (apply_patch.is_object()) + { + if (!is_object()) + { + *this = object(); + } + for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) + { + if (it.value().is_null()) + { + erase(it.key()); + } + else + { + operator[](it.key()).merge_patch(it.value()); + } + } + } + else + { + *this = apply_patch; + } + } + + /// @} +}; + +/*! +@brief user-defined to_string function for JSON values + +This function implements a user-defined to_string for JSON objects. + +@param[in] j a JSON object +@return a std::string object +*/ + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) +{ + return j.dump(); +} +} // namespace nlohmann + +/////////////////////// +// nonmember support // +/////////////////////// + +// specialization of std::swap, and std::hash +namespace std +{ + +/// hash value for JSON objects +template<> +struct hash +{ + /*! + @brief return a hash value for a JSON object + + @since version 1.0.0 + */ + std::size_t operator()(const nlohmann::json& j) const + { + return nlohmann::detail::hash(j); + } +}; + +/// specialization for std::less +/// @note: do not remove the space after '<', +/// see https://github.com/nlohmann/json/pull/679 +template<> +struct less<::nlohmann::detail::value_t> +{ + /*! + @brief compare two value_t enum values + @since version 3.0.0 + */ + bool operator()(nlohmann::detail::value_t lhs, + nlohmann::detail::value_t rhs) const noexcept + { + return nlohmann::detail::operator<(lhs, rhs); + } +}; + +// C++20 prohibit function specialization in the std namespace. +#ifndef JSON_HAS_CPP_20 + +/*! +@brief exchanges the values of two JSON objects + +@since version 1.0.0 +*/ +template<> +inline void swap(nlohmann::json& j1, nlohmann::json& j2) noexcept( + is_nothrow_move_constructible::value&& + is_nothrow_move_assignable::value + ) +{ + j1.swap(j2); +} + +#endif + +} // namespace std + +/*! +@brief user-defined string literal for JSON values + +This operator implements a user-defined string literal for JSON objects. It +can be used by adding `"_json"` to a string literal and returns a JSON object +if no parse error occurred. + +@param[in] s a string representation of a JSON object +@param[in] n the length of string @a s +@return a JSON object + +@since version 1.0.0 +*/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json operator "" _json(const char* s, std::size_t n) +{ + return nlohmann::json::parse(s, s + n); +} + +/*! +@brief user-defined string literal for JSON pointer + +This operator implements a user-defined string literal for JSON Pointers. It +can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer +object if no parse error occurred. + +@param[in] s a string representation of a JSON Pointer +@param[in] n the length of string @a s +@return a JSON pointer object + +@since version 2.0.0 +*/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return nlohmann::json::json_pointer(std::string(s, n)); +} + +// #include + + +// restore GCC/clang diagnostic settings +#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) + #pragma GCC diagnostic pop +#endif +#if defined(__clang__) + #pragma GCC diagnostic pop +#endif + +// clean up +#undef JSON_ASSERT +#undef JSON_INTERNAL_CATCH +#undef JSON_CATCH +#undef JSON_THROW +#undef JSON_TRY +#undef JSON_HAS_CPP_14 +#undef JSON_HAS_CPP_17 +#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION +#undef NLOHMANN_BASIC_JSON_TPL +#undef JSON_EXPLICIT + +// #include +#undef JSON_HEDLEY_ALWAYS_INLINE +#undef JSON_HEDLEY_ARM_VERSION +#undef JSON_HEDLEY_ARM_VERSION_CHECK +#undef JSON_HEDLEY_ARRAY_PARAM +#undef JSON_HEDLEY_ASSUME +#undef JSON_HEDLEY_BEGIN_C_DECLS +#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#undef JSON_HEDLEY_CLANG_HAS_FEATURE +#undef JSON_HEDLEY_CLANG_HAS_WARNING +#undef JSON_HEDLEY_COMPCERT_VERSION +#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#undef JSON_HEDLEY_CONCAT +#undef JSON_HEDLEY_CONCAT3 +#undef JSON_HEDLEY_CONCAT3_EX +#undef JSON_HEDLEY_CONCAT_EX +#undef JSON_HEDLEY_CONST +#undef JSON_HEDLEY_CONSTEXPR +#undef JSON_HEDLEY_CONST_CAST +#undef JSON_HEDLEY_CPP_CAST +#undef JSON_HEDLEY_CRAY_VERSION +#undef JSON_HEDLEY_CRAY_VERSION_CHECK +#undef JSON_HEDLEY_C_DECL +#undef JSON_HEDLEY_DEPRECATED +#undef JSON_HEDLEY_DEPRECATED_FOR +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#undef JSON_HEDLEY_DIAGNOSTIC_POP +#undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#undef JSON_HEDLEY_DMC_VERSION +#undef JSON_HEDLEY_DMC_VERSION_CHECK +#undef JSON_HEDLEY_EMPTY_BASES +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#undef JSON_HEDLEY_END_C_DECLS +#undef JSON_HEDLEY_FLAGS +#undef JSON_HEDLEY_FLAGS_CAST +#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_BUILTIN +#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_EXTENSION +#undef JSON_HEDLEY_GCC_HAS_FEATURE +#undef JSON_HEDLEY_GCC_HAS_WARNING +#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#undef JSON_HEDLEY_GCC_VERSION +#undef JSON_HEDLEY_GCC_VERSION_CHECK +#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#undef JSON_HEDLEY_GNUC_HAS_FEATURE +#undef JSON_HEDLEY_GNUC_HAS_WARNING +#undef JSON_HEDLEY_GNUC_VERSION +#undef JSON_HEDLEY_GNUC_VERSION_CHECK +#undef JSON_HEDLEY_HAS_ATTRIBUTE +#undef JSON_HEDLEY_HAS_BUILTIN +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_HAS_EXTENSION +#undef JSON_HEDLEY_HAS_FEATURE +#undef JSON_HEDLEY_HAS_WARNING +#undef JSON_HEDLEY_IAR_VERSION +#undef JSON_HEDLEY_IAR_VERSION_CHECK +#undef JSON_HEDLEY_IBM_VERSION +#undef JSON_HEDLEY_IBM_VERSION_CHECK +#undef JSON_HEDLEY_IMPORT +#undef JSON_HEDLEY_INLINE +#undef JSON_HEDLEY_INTEL_VERSION +#undef JSON_HEDLEY_INTEL_VERSION_CHECK +#undef JSON_HEDLEY_IS_CONSTANT +#undef JSON_HEDLEY_IS_CONSTEXPR_ +#undef JSON_HEDLEY_LIKELY +#undef JSON_HEDLEY_MALLOC +#undef JSON_HEDLEY_MESSAGE +#undef JSON_HEDLEY_MSVC_VERSION +#undef JSON_HEDLEY_MSVC_VERSION_CHECK +#undef JSON_HEDLEY_NEVER_INLINE +#undef JSON_HEDLEY_NON_NULL +#undef JSON_HEDLEY_NO_ESCAPE +#undef JSON_HEDLEY_NO_RETURN +#undef JSON_HEDLEY_NO_THROW +#undef JSON_HEDLEY_NULL +#undef JSON_HEDLEY_PELLES_VERSION +#undef JSON_HEDLEY_PELLES_VERSION_CHECK +#undef JSON_HEDLEY_PGI_VERSION +#undef JSON_HEDLEY_PGI_VERSION_CHECK +#undef JSON_HEDLEY_PREDICT +#undef JSON_HEDLEY_PRINTF_FORMAT +#undef JSON_HEDLEY_PRIVATE +#undef JSON_HEDLEY_PUBLIC +#undef JSON_HEDLEY_PURE +#undef JSON_HEDLEY_REINTERPRET_CAST +#undef JSON_HEDLEY_REQUIRE +#undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#undef JSON_HEDLEY_REQUIRE_MSG +#undef JSON_HEDLEY_RESTRICT +#undef JSON_HEDLEY_RETURNS_NON_NULL +#undef JSON_HEDLEY_SENTINEL +#undef JSON_HEDLEY_STATIC_ASSERT +#undef JSON_HEDLEY_STATIC_CAST +#undef JSON_HEDLEY_STRINGIFY +#undef JSON_HEDLEY_STRINGIFY_EX +#undef JSON_HEDLEY_SUNPRO_VERSION +#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#undef JSON_HEDLEY_TINYC_VERSION +#undef JSON_HEDLEY_TINYC_VERSION_CHECK +#undef JSON_HEDLEY_TI_ARMCL_VERSION +#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL2000_VERSION +#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL430_VERSION +#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL6X_VERSION +#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL7X_VERSION +#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CLPRU_VERSION +#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#undef JSON_HEDLEY_TI_VERSION +#undef JSON_HEDLEY_TI_VERSION_CHECK +#undef JSON_HEDLEY_UNAVAILABLE +#undef JSON_HEDLEY_UNLIKELY +#undef JSON_HEDLEY_UNPREDICTABLE +#undef JSON_HEDLEY_UNREACHABLE +#undef JSON_HEDLEY_UNREACHABLE_RETURN +#undef JSON_HEDLEY_VERSION +#undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#undef JSON_HEDLEY_VERSION_DECODE_MINOR +#undef JSON_HEDLEY_VERSION_DECODE_REVISION +#undef JSON_HEDLEY_VERSION_ENCODE +#undef JSON_HEDLEY_WARNING +#undef JSON_HEDLEY_WARN_UNUSED_RESULT +#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#undef JSON_HEDLEY_FALL_THROUGH + + + +#endif // INCLUDE_NLOHMANN_JSON_HPP_ diff --git a/external/libhv/libhv-1.3.2/cpputil/singleton.h b/external/libhv/libhv-1.3.2/cpputil/singleton.h new file mode 100644 index 0000000..9553b01 --- /dev/null +++ b/external/libhv/libhv-1.3.2/cpputil/singleton.h @@ -0,0 +1,41 @@ +#ifndef HV_SINGLETON_H_ +#define HV_SINGLETON_H_ + +#include + +#define DISABLE_COPY(Class) \ + Class(const Class&) = delete; \ + Class& operator=(const Class&) = delete; + +#define SINGLETON_DECL(Class) \ + public: \ + static Class* instance(); \ + static void exitInstance(); \ + private: \ + DISABLE_COPY(Class) \ + static Class* s_pInstance; \ + static std::mutex s_mutex; + +#define SINGLETON_IMPL(Class) \ + Class* Class::s_pInstance = NULL; \ + std::mutex Class::s_mutex; \ + Class* Class::instance() { \ + if (s_pInstance == NULL) { \ + s_mutex.lock(); \ + if (s_pInstance == NULL) { \ + s_pInstance = new Class; \ + } \ + s_mutex.unlock(); \ + } \ + return s_pInstance; \ + } \ + void Class::exitInstance() { \ + s_mutex.lock(); \ + if (s_pInstance) { \ + delete s_pInstance; \ + s_pInstance = NULL; \ + } \ + s_mutex.unlock(); \ + } + +#endif // HV_SINGLETON_H_ diff --git a/external/libhv/libhv-1.3.2/docs/API.md b/external/libhv/libhv-1.3.2/docs/API.md new file mode 100644 index 0000000..043d496 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/API.md @@ -0,0 +1,652 @@ +# libhv API Manual + +## base + +### hplatform.h +- OS: OS_WIN, OS_UNIX (OS_LINUX, OS_ANDROID, OS_DARWIN ...) +- ARCH: ARCH_X86, ARCH_X64, ARCH_ARM, ARCH_ARM64 +- COMPILER: COMPILER_MSVC, COMPILER_MINGW, COMPILER_GCC, COMPILER_CLANG +- BYTE_ORDER: BIG_ENDIAN, LITTLE_ENDIAN +- stdbool.h: bool, true, false +- stdint.h: int8_t, int16_t, int32_t, int64_t +- hv_sleep, hv_msleep, hv_usleep, hv_delay +- hv_mkdir +- stricmp, strcasecmp + +### hexport.h +- HV_EXPORT, HV_INLINE +- HV_SOURCE, HV_STATICLIB, HV_DYNAMICLIB +- HV_DEPRECATED +- HV_UNUSED +- EXTERN_C, BEGIN_EXTERN_C, END_EXTERN_C +- BEGIN_NAMESPACE, END_NAMESPACE, USING_NAMESPACE +- DEFAULT +- ENUM, STRUCT +- IN, OUT, INOUT +- OPTIONAL, REQUIRED, REPEATED + +### hdef.h +- ABS, NABS +- ARRAY_SIZE +- BITSET, BITCLR, BITGET +- CR, LF, CRLF +- FLOAT_EQUAL_ZERO +- INFINITE +- IS_ALPHA, IS_DIGIT, IS_ALPHANUM +- IS_CNTRL, IS_GRAPH +- IS_HEX +- IS_LOWER, IS_UPPER +- LOWER, UPPER +- MAKEWORD, LOBYTE, HIBYTE +- MAKELONG, LOWORD, HIWORD +- MAKEINT64, LOINT, HIINT +- MAKE_FOURCC +- MAX, MIN, LIMIT +- MAX_PATH +- NULL, TRUE, FALSE +- SAFE_FREE, SAFE_DELETE, SAFE_DELETE_ARRAY, SAFE_RELEASE +- STRINGCAT +- STRINGIFY +- offsetof, offsetofend +- container_of +- prefetch +- printd, printe + +### hatomic.h +- hatomic_flag_t, hatomic_t +- hatomic_flag_test_and_set +- hatomic_flag_clear +- hatomic_add +- hatomic_sub +- hatomic_inc +- hatomic_dec + +### herr.h +- hv_strerror + +### htime.h +- IS_LEAP_YEAR +- datetime_t +- gettick_ms +- gettimeofday +- gettimeofday_ms +- gettimeofday_us +- gethrtime_us +- datetime_now +- datetime_localtime +- datetime_mktime +- datetime_past +- datetime_future +- duration_fmt +- datetime_fmt +- gmtime_fmt +- days_of_month +- month_atoi +- month_itoa +- weekday_atoi +- weekday_itoa +- hv_compile_datetime +- cron_next_timeout + +### hmath.h +- floor2e +- ceil2e +- varint_encode +- varint_decode + +### hbase.h +- hv_malloc +- hv_calloc +- hv_realloc +- hv_zalloc +- hv_strncpy +- hv_strncat +- hv_strlower +- hv_strupper +- hv_strreverse +- hv_strstartswith +- hv_strendswith +- hv_strcontains +- hv_wildcard_match +- hv_strnchr +- hv_strrchr_dot +- hv_strrchr_dir +- hv_basename +- hv_suffixname +- hv_mkdir_p +- hv_rmdir_p +- hv_exists +- hv_isdir +- hv_isfile +- hv_islink +- hv_filesize +- get_executable_path +- get_executable_dir +- get_executable_file +- get_run_dir +- hv_rand +- hv_random_string +- hv_getboolean +- hv_parse_size +- hv_parse_time +- hv_parse_url + +### hversion.h +- hv_version +- hv_compile_version +- version_atoi +- version_itoa + +### hsysinfo.h +- get_ncpu +- get_meminfo + +### hproc.h +- hproc_spawn + +### hthread.h +- hv_getpid +- hv_gettid +- HTHREAD_RETTYPE +- HTHREAD_ROUTINE +- hthread_create +- hthread_join +- class HThread + +### hmutex.h +- hmutex_t +- hmutex_init +- hmutex_destroy +- hmutex_lock +- hmutex_unlock +- hspinlock_t +- hspinlock_init +- hspinlock_destroy +- hspinlock_lock +- hspinlock_unlock +- hrwlock_t +- hrwlock_init +- hrwlock_destroy +- hrwlock_rdlock +- hrwlock_rdunlock +- hrwlock_wrlock +- hrwlock_wrunlock +- htimed_mutex_t +- htimed_mutex_init +- htimed_mutex_destroy +- htimed_mutex_lock +- htimed_mutex_lock_for +- htimed_mutex_unlock +- hcondvar_t +- hcondvar_init +- hcondvar_destroy +- hcondvar_wait +- hcondvar_wait_for +- hcondvar_signal +- hcondvar_broadcast +- hsem_init +- hsem_destroy +- hsem_wait +- hsem_post +- hsem_timedwait +- honce_t +- HONCE_INIT +- honce +- class `hv::MutexLock` +- class `hv::SpinLock` +- class `hv::RWLock` +- class `hv::LockGuard` +- synchronized + +### hsocket.h +- INVALID_SOCKET +- closesocket +- blocking +- nonblocking +- Bind +- Listen +- Connect +- ConnectNonblock +- ConnectTimeout +- ResolveAddr +- Socketpair +- socket_errno +- socket_strerror +- sockaddr_u +- sockaddr_ip +- sockaddr_port +- sockaddr_set_ip +- sockaddr_set_port +- sockaddr_set_ipport +- sockaddr_len +- sockaddr_str +- sockaddr_print +- SOCKADDR_LEN +- SOCKADDR_STR +- SOCKADDR_PRINT +- tcp_nodelay +- tcp_nopush +- tcp_keepalive +- udp_broadcast +- ip_v6only +- so_sndtimeo +- so_rcvtimeo +- so_sndbuf +- so_rcvbuf +- so_reuseaddr +- so_reuseport +- so_linger + +### hlog.h +- default_logger +- file_logger +- stderr_logger +- stdout_logger +- logger_create +- logger_destroy +- logger_enable_color +- logger_enable_fsync +- logger_fsync +- logger_print +- logger_set_file +- logger_set_handler +- logger_set_level +- logger_set_max_bufsize +- logger_set_max_filesize +- logger_set_remain_days +- logger_get_cur_file +- hlogd, hlogi, hlogw, hloge, hlogf +- LOGD, LOGI, LOGW, LOGE, LOGF + +### hbuf.h +- hbuf_t +- offset_buf_t +- class HBuf +- class HVLBuf +- class HRingBuf + +### hmain.h +- main_ctx_init +- parse_opt +- parse_opt_long +- get_arg +- get_env +- setproctitle +- signal_init +- signal_handle +- create_pidfile +- delete_pidfile +- getpid_form_pidfile +- master_workers_run + +### hstring.h +- to_string +- from_string +- toupper +- tolower +- reverse +- startswith +- endswith +- contains +- asprintf +- trim +- ltrim +- rtrim +- trim_pairs +- split +- splitKV +- replace +- replaceAll + +### hfile.h +- class HFile + +### hpath.h +- exists +- isdir +- isfile +- islink +- basename +- dirname +- filename +- suffixname +- join + +### hdir.h +- listdir + +### hurl.h +- HUrl::escape +- HUrl::unescape +- HUrl::parse +- HUrl::dump + +### hscope.h +- defer +- template ScopeCleanup +- template ScopeFree +- template ScopeDelete +- template ScopeDeleteArray +- template ScopeRelease +- template ScopeLock + +### ifconfig.h +- ifconfig + +## utils +### md5.h +- HV_MD5Init +- HV_MD5Update +- HV_MD5Final +- hv_md5 +- hv_md5_hex + +### sha1.h +- HV_SHA1Init +- HV_SHA1Update +- HV_SHA1Final +- HV_SHA1 +- hv_sha1 +- hv_sha1_hex + +### base64.h +- hv_base64_decode +- hv_base64_encode + +### json.hpp +- json::parse +- json::dump + +### singleton.h +- DISABLE_COPY +- SINGLETON_DECL +- SINGLETON_IMPL + +## event + +### hloop.h +- hloop_create_tcp_client +- hloop_create_tcp_server +- hloop_create_udp_client +- hloop_create_udp_server +- hloop_create_ssl_client +- hloop_create_ssl_server +- hloop_new +- hloop_free +- hloop_run +- hloop_stop +- hloop_pause +- hloop_resume +- hloop_status +- hloop_pid +- hloop_tid +- hloop_now +- hloop_now_ms +- hloop_now_us +- hloop_update_time +- hloop_set_userdata +- hloop_userdata +- hloop_wakeup +- hloop_post_event +- hevent_loop +- hevent_type +- hevent_id +- hevent_priority +- hevent_userdata +- hevent_set_priority +- hevent_ser_userdata +- haccept +- hconnect +- hread +- hwrite +- hrecv +- hsend +- hrecvfrom +- hsendto +- hio_add +- hio_del +- hio_get +- hio_detach +- hio_attach +- hio_read +- hio_read_start +- hio_read_stop +- hio_read_once +- hio_read_until +- hio_read_until_length +- hio_read_until_delim +- hio_read_readline +- hio_read_readstring +- hio_read_readbytes +- hio_write +- hio_close +- hio_accept +- hio_connect +- hio_fd +- hio_id +- hio_type +- hio_error +- hio_localaddr +- hio_peeraddr +- hio_events +- hio_revents +- hio_is_opened +- hio_is_closed +- hio_enable_ssl +- hio_is_ssl +- hio_get_ssl +- hio_set_ssl +- hio_get_ssl_ctx +- hio_set_ssl_ctx +- hio_new_ssl_ctx +- hio_setcb_accept +- hio_setcb_connect +- hio_setcb_read +- hio_setcb_write +- hio_setcb_close +- hio_getcb_accept +- hio_getcb_connect +- hio_getcb_read +- hio_getcb_write +- hio_getcb_close +- hio_set_type +- hio_set_localaddr +- hio_set_peeraddr +- hio_set_readbuf +- hio_set_connect_timeout +- hio_set_close_timeout +- hio_set_read_timeout +- hio_set_write_timeout +- hio_set_keepalive_timeout +- hio_set_heartbeat +- hio_set_unpack +- hio_unset_unpack +- hio_read_upstream +- hio_write_upstream +- hio_close_upstream +- hio_setup_upstream +- hio_get_upstream +- hio_setup_tcp_upstream +- hio_setup_ssl_upstream +- hio_setup_udp_upstream +- hio_create_socket +- hio_context +- hio_set_context +- htimer_add +- htimer_add_period +- htimer_del +- htimer_reset +- hidle_add +- hidle_del + +### nlog.h +- network_logger +- nlog_listen + +## evpp +- class Buffer +- class Channel +- class Event +- class EventLoop +- class EventLoopThread +- class EventLoopThreadPool +- class TcpClient +- class TcpServer +- class UdpClient +- class UdpServer + +## ssl +- hssl_ctx_init +- hssl_ctx_cleanup +- hssl_ctx_instance +- hssl_ctx_new +- hssl_ctx_free +- hssl_new +- hssl_free +- hssl_accept +- hssl_connnect +- hssl_read +- hssl_write +- hssl_close +- hssl_set_sni_hostname + +## protocol + +### dns.h +- dns_name_decode +- dns_name_encode +- dns_pack +- dns_unpack +- dns_rr_pack +- dns_rr_unpack +- dns_query +- dns_free +- nslookup + +### ftp.h +- ftp_command_str +- ftp_connect +- ftp_login +- ftp_exec +- ftp_upload +- ftp_download +- ftp_download_with_cb +- ftp_quit +- ftp_status_str + +### smtp.h +- smtp_command_str +- smtp_status_str +- smtp_build_command +- sendmail + +### icmp.h +- ping + +## http +- class HttpMessage +- class HttpRequest +- class HttpResponse +- class HttpParser + +### httpdef.h +- http_content_type_enum +- http_content_type_enum_by_suffix +- http_content_type_str +- http_content_type_str_by_suffix +- http_content_type_suffix +- http_errno_description +- http_errno_name +- http_method_enum +- http_method_str +- http_status_enum +- http_status_str + +### http_content.h +- parse_query_params +- parse_json +- parse_multipart +- dump_query_params +- dump_json +- dump_multipart + +### HttpClient.h +- http_client_new +- http_client_del +- http_client_send +- http_client_send_async +- http_client_strerror +- http_client_set_timeout +- http_client_set_header +- http_client_del_header +- http_client_get_header +- http_client_clear_headers +- http_client_set_http_proxy +- http_client_set_https_proxy +- http_client_add_no_proxy +- class HttpClient + +### requests.h +- requests::request +- requests::get +- requests::post +- requests::put +- requests::patch +- requests::Delete +- requests::head +- requests::async + +### axios.h +- axios::axios +- axios::get +- axios::post +- axios::put +- axios::patch +- axios::Delete +- axios::head +- axios::async + +### HttpServer.h +- http_server_run +- http_server_stop +- class HttpService +- class HttpServer + +### WebSocketClient.h +- class WebSocketClient + +### WebSocketServer.h +- websocket_server_run +- websocket_server_stop +- class WebSocketService +- class WebSocketServer + +## mqtt +- mqtt_client_new +- mqtt_client_free +- mqtt_client_run +- mqtt_client_stop +- mqtt_client_set_id +- mqtt_client_set_will +- mqtt_client_set_auth +- mqtt_client_set_callback +- mqtt_client_set_userdata +- mqtt_client_get_userdata +- mqtt_client_get_last_error +- mqtt_client_set_ssl_ctx +- mqtt_client_new_ssl_ctx +- mqtt_client_set_reconnect +- mqtt_client_reconnect +- mqtt_client_set_connect_timeout +- mqtt_client_connect +- mqtt_client_is_connected +- mqtt_client_disconnect +- mqtt_client_publish +- mqtt_client_subscribe +- mqtt_client_unsubscribe +- class MqttClient + +## other +- class HThreadPool +- class HObjectPool +- class ThreadLocalStorage diff --git a/external/libhv/libhv-1.3.2/docs/PLAN.md b/external/libhv/libhv-1.3.2/docs/PLAN.md new file mode 100644 index 0000000..d47fc50 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/PLAN.md @@ -0,0 +1,31 @@ +## Done + +- base: cross platfrom infrastructure +- event: select/poll/epoll/wepoll/kqueue/port +- ssl: openssl/gnutls/mbedtls/wintls/appletls +- rudp: KCP +- evpp: c++ EventLoop interface similar to muduo and evpp +- http client/server: include https http1/x http2 +- websocket client/server +- mqtt client + +## Improving + +- Path router: optimized matching via trie? +- FileCache use LRUCache + +## Plan + +- redis client +- async DNS +- lua binding +- js binding +- hrpc = libhv + protobuf +- rudp: FEC, ARQ, UDT, QUIC +- kcptun +- have a taste of io_uring +- coroutine +- cppsocket.io +- IM-libhv +- MediaServer-libhv +- GameServer-libhv diff --git a/external/libhv/libhv-1.3.2/docs/cn/Channel.md b/external/libhv/libhv-1.3.2/docs/cn/Channel.md new file mode 100644 index 0000000..f48a60a --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/Channel.md @@ -0,0 +1,153 @@ +通道类 + +```c++ + +class Channel { + + // 返回底层的io结构体指针 + hio_t* io() { return io_; } + + // 返回socket文件描述符 + int fd() { return fd_; } + + // 返回一个唯一标示id + uint32_t id() { return id_; } + + // 返回错误码 + int error() { return hio_error(io_); } + + // 获取/设置/新建/删除 上下文 + void* context(); + void setContext(void* ctx); + template T* newContext(); + template T* getContext(); + template void deleteContext(); + + // 获取/设置/新建/删除 上下文智能指针 + std::shared_ptr contextPtr(); + void setContextPtr(const std::shared_ptr& ctx); + void setContextPtr(std::shared_ptr&& ctx); + template std::shared_ptr newContextPtr(); + template std::shared_ptr getContextPtr(); + void deleteContextPtr(); + + // 是否打开状态 + bool isOpened(); + + // 是否关闭状态 + bool isClosed(); + + // 开始读 + int startRead(); + + // 停止读 + int stopRead(); + + // 读一次 + int readOnce(); + // 读一个字符串 + int readString(); + // 读一行 + int readLine(); + // 读取N个字节 + int readBytes(int len); + + // 写 + int write(const void* data, int size); + int write(Buffer* buf); + int write(const std::string& str); + + // 设置最大读缓存 + void setMaxReadBufsize(uint32_t size); + // 设置最大写缓存 + void setMaxWriteBufsize(uint32_t size); + // 获取当前写缓存大小 + size_t writeBufsize(); + // 是否写完成 + bool isWriteComplete(); + + // 关闭 + int close(bool async = false); + + // 读回调 + std::function onread; + // 写回调 + std::function onwrite; + // 关闭回调 + std::function onclose; +}; + +// SocketChannel 继承自 Channel +class SocketChannel : public Channel { + // 连接状态回调 + std::function onconnect; + // 心跳回调 + std::function heartbeat; + + // 启用SSL/TLS加密通信 + int enableSSL(); + // 是否是SSL/TLS加密通信 + bool isSSL(); + // 设置SSL + int setSSL(hssl_t ssl); + // 设置SSL_CTX + int setSslCtx(hssl_ctx_t ssl_ctx); + // 新建SSL_CTX + int newSslCtx(hssl_ctx_opt_t* opt); + // 设置主机名 + int setHostname(const std::string& hostname); + + // 设置连接超时 + void setConnectTimeout(int timeout_ms); + + // 设置关闭超时 (说明:非阻塞写队列非空时,需要等待写完成再关闭) + void setCloseTimeout(int timeout_ms); + + // 设置读超时 (一段时间没有数据到来便自动关闭连接) + void setReadTimeout(int timeout_ms); + + // 设置写超时 (一段时间没有数据发送便自动关闭连接) + void setWriteTimeout(int timeout_ms); + + // 设置keepalive超时 (一段时间没有数据收发便自动关闭连接) + void setKeepaliveTimeout(int timeout_ms); + + // 设置心跳 (定时发送心跳包) + void setHeartbeat(int interval_ms, std::function fn); + + // 设置拆包规则 + void setUnpack(unpack_setting_t* setting); + + // 开始连接 + int startConnect(int port, const char* host = "127.0.0.1"); + int startConnect(struct sockaddr* peeraddr); + int startConnect(); + + // 是否已连接 + bool isConnected(); + + // 返回本地地址 + std::string localaddr(); + + // 返回对端地址 + std::string peeraddr(); +}; + +// WebSocketChannel 继承自 SocketChannel +class WebSocketChannel : public SocketChannel { + + // 发送文本帧 + int send(const std::string& msg, enum ws_opcode opcode = WS_OPCODE_TEXT, bool fin = true); + + // 发送二进制帧 + int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); + + // 分片发送 + int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY); + + // 关闭 + int close(); + +}; + +``` diff --git a/external/libhv/libhv-1.3.2/docs/cn/EventLoop.md b/external/libhv/libhv-1.3.2/docs/cn/EventLoop.md new file mode 100644 index 0000000..fe4181b --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/EventLoop.md @@ -0,0 +1,123 @@ +事件循环类 + +```c++ + +class EventLoop { + + // 返回底层的loop结构体指针 + hloop_t* loop(); + + // 运行 + void run(); + // 停止 + void stop(); + // 暂停 + void pause(); + // 继续 + void resume(); + + // 设置定时器 + TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID); + + // 设置一次性定时器 + TimerID setTimeout(int timeout_ms, TimerCallback cb); + + // 设置永久性定时器 + TimerID setInterval(int interval_ms, TimerCallback cb); + + // 杀掉定时器 + void killTimer(TimerID timerID); + + // 重置定时器 + void resetTimer(TimerID timerID, int timeout_ms = 0); + + // 返回事件循环所在的线程ID + long tid(); + + // 是否在事件循环所在线程 + bool isInLoopThread(); + + // 断言在事件循环所在线程 + void assertInLoopThread(); + + // 运行在事件循环里 + void runInLoop(Functor fn); + + // 队列在事件循环里 + void queueInLoop(Functor fn); + + // 投递一个事件到事件循环 + void postEvent(EventCallback cb); + +}; + +class EventLoopThread { + + // 返回事件循环指针 + const EventLoopPtr& loop(); + + // 返回底层的loop结构体指针 + hloop_t* hloop(); + + // 是否运行中 + bool isRunning(); + + /* 开始运行 + * wait_thread_started: 是否阻塞等待线程开始 + * pre: 线程开始后执行的函数 + * post: 线程结束前执行的函数 + */ + void start(bool wait_thread_started = true, + Functor pre = Functor(), + Functor post = Functor()); + + // 停止运行 + void stop(bool wait_thread_stopped = false); + + // 等待线程退出 + void join(); + +}; + +class EventLoopThreadPool { + + // 获取线程数量 + int threadNum(); + + // 设置线程数量 + void setThreadNum(int num); + + // 返回下一个事件循环对象 + // 支持轮询、随机、最少连接数等负载均衡策略 + EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin); + + // 返回索引的事件循环对象 + EventLoopPtr loop(int idx = -1); + + // 返回索引的底层loop结构体指针 + hloop_t* hloop(int idx = -1); + + /* 开始运行 + * wait_threads_started: 是否阻塞等待所有线程开始 + * pre: 线程开始后执行的函数 + * post: 线程结束前执行的函数 + */ + void start(bool wait_threads_started = false, + std::function pre = NULL, + std::function post = NULL); + + // 停止运行 + void stop(bool wait_threads_stopped = false); + + // 等待所有线程退出 + void join(); + +}; + +``` + +测试代码见: + +- [evpp/EventLoop_test.cpp](../../evpp/EventLoop_test.cpp) +- [evpp/EventLoopThread_test.cpp](../../evpp/EventLoopThread_test.cpp) +- [evpp/EventLoopThreadPool_test.cpp](../../evpp/EventLoopThreadPool_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/HttpClient.md b/external/libhv/libhv-1.3.2/docs/cn/HttpClient.md new file mode 100644 index 0000000..d67b57e --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/HttpClient.md @@ -0,0 +1,84 @@ +HTTP 客户端类 + +```c++ + +class HttpClient { + + // 设置超时 + int setTimeout(int timeout); + + // 设置SSL/TLS + int setSslCtx(hssl_ctx_t ssl_ctx); + // 新建SSL/TLS + int newSslCtx(hssl_ctx_opt_t* opt); + + // 清除全部请求头部 + int clearHeaders(); + // 设置请求头部 + int setHeader(const char* key, const char* value); + // 删除请求头部 + int delHeader(const char* key); + // 获取请求头部 + const char* getHeader(const char* key); + + // 设置http代理 + int setHttpProxy(const char* host, int port); + // 设置https代理 + int setHttpsProxy(const char* host, int port); + // 添加不走代理 + int addNoProxy(const char* host); + + // 同步发送 + int send(HttpRequest* req, HttpResponse* resp); + // 异步发送 + int sendAsync(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); + + // 关闭连接 (HttpClient对象析构时会自动调用) + int close(); + +}; + +namespace requests { + + // 同步请求 + Response request(Request req); + Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); + + // 上传文件 + Response uploadFile(const char* url, const char* filepath, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); + + // 通过 `multipart/form-data` 格式上传文件 + Response uploadFormFile(const char* url, const char* name, const char* filepath, std::map& params = hv::empty_map, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); + + // 上传大文件(带上传进度回调) + Response uploadLargeFile(const char* url, const char* filepath, upload_progress_cb progress_cb = NULL, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders); + + // 下载文件 (更详细的断点续传示例代码见`examples/wget.cpp`) + size_t downloadFile(const char* url, const char* filepath, download_progress_cb progress_cb = NULL); + + // HEAD 请求 + Response head(const char* url, const http_headers& headers = DefaultHeaders); + + // GET 请求 + Response get(const char* url, const http_headers& headers = DefaultHeaders); + + // POST 请求 + Response post(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); + + // PUT 请求 + Response put(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); + + // PATCH 请求 + Response patch(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders); + + // DELETE 请求 + Response Delete(const char* url, const http_headers& headers = DefaultHeaders); + + // 异步请求 + int async(Request req, ResponseCallback resp_cb); + +} + +``` + +测试代码见 [examples/http_client_test.cpp](../../examples/http_client_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/HttpContext.md b/external/libhv/libhv-1.3.2/docs/cn/HttpContext.md new file mode 100644 index 0000000..13cf85f --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/HttpContext.md @@ -0,0 +1,83 @@ +```c++ + +class HttpContext { + + /* 获取请求信息 */ + // 获取客户端IP + std::string ip(); + // 获取客户端端口 + int port(); + // 获取请求method + http_method method(); + // 获取请求url + std::string url(); + // 获取请求path + std::string path(); + // 获取请求host + std::string host(); + // 获取请求头部 + const http_headers& headers(); + std::string header(const char* key, const std::string& defvalue = hv::empty_string); + // 获取请求参数 + const hv::QueryParams& params(); + std::string param(const char* key, const std::string& defvalue = hv::empty_string); + // 获取请求cookie + const HttpCookie& cookie(const char* name); + // 获取请求 `Content-Length` + int length(); + // 获取请求 `Content-Type` + http_content_type type(); + // 判断请求 `Content-Type` + bool is(http_content_type content_type); + // 获取请求body + std::string& body(); + // 获取 `application/json` 格式数据 + const hv::Json& json(); + // 获取 `multipart/form-data` 格式数据 + const hv::MultiPart& form(); + std::string form(const char* name, const std::string& defvalue = hv::empty_string); + // 获取 `application/x-www-urlencoded` 格式数据 + const hv::KeyValue& urlencoded(); + std::string urlencoded(const char* key, const std::string& defvalue = hv::empty_string); + // 根据 `Content-Type` 获取对应格式数据 + template + T get(const char* key, T defvalue = 0); + std::string get(const char* key, const std::string& defvalue = hv::empty_string); + + /* 设置响应信息 */ + // 设置响应状态码 + void setStatus(http_status status); + // 设置响应 `Content-Type` + void setContentType(http_content_type type); + // 设置响应头部 + void setHeader(const char* key, const std::string& value); + // 设置响应cookie + void setCookie(const HttpCookie& cookie); + // 设置响应body + void setBody(const std::string& body); + template + // 根据 `Content-Type` 设置对应格式数据 + void set(const char* key, const T& value); + + // 发送 + int send(); + int send(const std::string& str, http_content_type type = APPLICATION_JSON); + // 发送文本数据 + int sendString(const std::string& str); + // 发送二进制数据 + int sendData(void* data, int len, bool nocopy = true); + // 发送文件 + int sendFile(const char* filepath); + // 发送json数据 + template + int sendJson(const T& t); + + // 重定向 + int redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND); + + // 主动关闭连接 + int close(); + +}; + +``` diff --git a/external/libhv/libhv-1.3.2/docs/cn/HttpMessage.md b/external/libhv/libhv-1.3.2/docs/cn/HttpMessage.md new file mode 100644 index 0000000..e6cd4e0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/HttpMessage.md @@ -0,0 +1,110 @@ +```c++ + +class HttpMessage { + // 设置/获取头部 + void SetHeader(const char* key, const std::string& value); + std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string); + + // 添加/获取cookie + void AddCookie(const HttpCookie& cookie); + const HttpCookie& GetCookie(const std::string& name); + + // 设置/获取 `Content-Type` + void SetContentType(http_content_type type); + http_content_type ContentType(); + + // 获取 `Content-Length` + size_t ContentLength(); + + // 填充数据 + void SetBody(const std::string& body); + // 获取数据 + const std::string& Body(); + // 解析数据 + int ParseBody(); + + // 填充/获取 `application/json` 格式数据 + template + int Json(const T& t); + const hv::Json& GetJson(); + + // 填充/获取 `multipart/form-data` 格式数据 + template + void SetFormData(const char* name, const T& t); + void SetFormFile(const char* name, const char* filepath); + std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string); + int SaveFormFile(const char* name, const char* path); + + // 填充/获取 `application/x-www-urlencoded` 格式数据 + template + void SetUrlEncoded(const char* key, const T& t); + std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string); + + // 根据 `Content-Type` 填充对应格式数据 + template + void Set(const char* key, const T& value); + // 根据 `Content-Type` 获取对应格式数据 + template + T Get(const char* key, T defvalue = 0); + // 根据 `Content-Type` 获取对应格式数据并转换成字符串 + std::string GetString(const char* key, const std::string& = ""); + // 根据 `Content-Type` 获取对应格式数据并转换成Boolean类型 + bool GetBool(const char* key, bool defvalue = 0); + // 根据 `Content-Type` 获取对应格式数据并转换成整型 + int64_t GetInt(const char* key, int64_t defvalue = 0); + // 根据 `Content-Type` 获取对应格式数据并转换成浮点数 + double GetFloat(const char* key, double defvalue = 0); +}; + +// HttpRequest 继承自 HttpMessage +class HttpRequest : public HttpMessage { + // 设置/获取method + void SetMethod(const char* method); + const char* Method(); + + // 设置URL + void SetUrl(const char* url); + // 获取URL + const std::string& Url(); + // 解析URL + void ParseUrl(); + // 获取Host + std::string Host(); + // 获取Path + std::string Path(); + + // 设置/获取参数 + template + void SetParam(const char* key, const T& t); + std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string); + + // 设置代理 + void SetProxy(const char* host, int port); + + // 设置认证 + void SetAuth(const std::string& auth); + void SetBasicAuth(const std::string& username, const std::string& password); + void SetBearerTokenAuth(const std::string& token); + + // 设置请求超时 + void SetTimeout(int sec); + // 设置连接超时 + void SetConnectTimeout(int sec); + // 允许重定向 + void AllowRedirect(bool on = true); + // 设置重试 + void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT, + int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY); + // 取消 + void Cancel(); +}; + +// HttpResponse 继承自 HttpMessage +class HttpResponse : public HttpMessage { + // 状态码 + http_status status_code; + // 状态字符串 + const char* status_message(); +}; + +``` diff --git a/external/libhv/libhv-1.3.2/docs/cn/HttpServer.md b/external/libhv/libhv-1.3.2/docs/cn/HttpServer.md new file mode 100644 index 0000000..13cae4d --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/HttpServer.md @@ -0,0 +1,140 @@ +HTTP 服务端类 + +```c++ + +// HTTP服务类 +class HttpServer { + + // 注册HTTP业务类 + void registerHttpService(HttpService* service); + + // 设置监听主机 + void setHost(const char* host = "0.0.0.0"); + // 设置监听端口 + void setPort(int port = 0, int ssl_port = 0); + // 设置监听文件描述符 + void setListenFD(int fd = -1, int ssl_fd = -1); + + // 设置IO进程数 (仅`linux`下有效) + void setProcessNum(int num); + // 设置IO线程数 + void setThreadNum(int num); + + // 设置SSL/TLS + int setSslCtx(hssl_ctx_t ssl_ctx); + // 新建SSL/TLS + int newSslCtx(hssl_ctx_opt_t* opt); + + // hooks + // 事件循环开始时执行的回调函数 + std::function onWorkerStart; + // 事件循环结束时执行的回调函数 + std::function onWorkerStop; + + // 占用当前线程运行 + int run(bool wait = true); + + // 不占用当前线程运行 + int start(); + + // 停止服务 + int stop(); + +}; + +// HTTP业务类 +class HttpService { + + // 添加静态资源映射 + void Static(const char* path, const char* dir); + + // 允许跨域访问 + void AllowCORS(); + + // 添加可信代理 (代理白名单) + void AddTrustProxy(const char* host); + + // 添加不可信代理 (代理黑名单) + void AddNoProxy(const char* host); + + // 开启正向转发代理 + void EnableForwardProxy(); + + // 添加反向代理映射 + void Proxy(const char* path, const char* url); + + // 添加中间件 + void Use(Handler handlerFunc); + + // 添加路由处理器 + void Handle(const char* httpMethod, const char* relativePath, Handler handlerFunc); + + // 添加`HEAD`路由 + void HEAD(const char* relativePath, Handler handlerFunc); + + // 添加`GET`路由 + void GET(const char* relativePath, Handler handlerFunc); + + // 添加`POST`路由 + void POST(const char* relativePath, Handler handlerFunc); + + // 添加`PUT`路由 + void PUT(const char* relativePath, Handler handlerFunc); + + // 添加`DELETE`路由 + void Delete(const char* relativePath, Handler handlerFunc); + + // 添加`PATCH`路由 + void PATCH(const char* relativePath, Handler handlerFunc); + + // 添加任意`HTTP method`路由 + void Any(const char* relativePath, Handler handlerFunc); + + // 返回注册的路由路径列表 + hv::StringList Paths(); + + // 处理流程:前处理器 -> 中间件 -> 处理器 -> 后处理器 + // preprocessor -> middleware -> processor -> postprocessor + + // 数据成员 + http_handler preprocessor; // 前处理器 + http_handlers middleware; // 中间件 + http_handler processor; // 处理器 + http_handler postprocessor; // 后处理器 + std::string base_url; // 基本路径 + std::string document_root; // 文档根目录 + std::string home_page; // 主页 + std::string error_page; // 默认错误页 + std::string index_of; // 目录 + http_handler errorHandler; // 错误处理器 + + int proxy_connect_timeout; // 代理连接超时 + int proxy_read_timeout; // 代理读超时 + int proxy_write_timeout; // 代理写超时 + + int keepalive_timeout; // 长连接保活超时 + int max_file_cache_size; // 文件缓存最大尺寸 + int file_cache_stat_interval; // 文件缓存stat间隔,查询文件是否修改 + int file_cache_expired_time; // 文件缓存过期时间,过期自动释放 + + int limit_rate; // 下载速度限制 + +}; + +/* 几种`handler`处理函数区别说明: */ + +// 同步`handler`运行在IO线程 +typedef std::function http_sync_handler; + +// 异步`handler`运行在`hv::async`全局线程池,可通过`hv::async::startup`设置线程池属性 +typedef std::function http_async_handler; + +// 上下文`handler`运行在IO线程,你可以很方便的将`HttpContextPtr`智能指针抛到你的消费者线程/线程池去处理 +typedef std::function http_ctx_handler; + +// 中间状态`handler`运行在IO线程,用来实现大数据量的边接收边处理 +typedef std::function http_state_handler; + +``` + +测试代码见 [examples/http_server_test.cpp](../../examples/http_server_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/README.md b/external/libhv/libhv-1.3.2/docs/cn/README.md new file mode 100644 index 0000000..d93c806 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/README.md @@ -0,0 +1,18 @@ +## c接口 + +- [hloop: 事件循环](hloop.md) +- [hbase: 基础函数](hbase.md) +- [hlog: 日志](hlog.md) + +## c++接口 + +- [class EventLoop: 事件循环类](EventLoop.md) +- [class Channel: 通道类](Channel.md) +- [class TcpServer: TCP服务端类](TcpServer.md) +- [class TcpClient: TCP客户端类](TcpClient.md) +- [class UdpServer: UDP服务端类](UdpServer.md) +- [class UdpClient: UDP客户端类](UdpClient.md) +- [class HttpServer: HTTP服务端类](HttpServer.md) +- [class HttpClient: HTTP客户端类](HttpClient.md) +- [class WebSocketServer: WebSocket服务端类](WebSocketServer.md) +- [class WebSocketClient: WebSocket客户端类](WebSocketClient.md) diff --git a/external/libhv/libhv-1.3.2/docs/cn/TcpClient.md b/external/libhv/libhv-1.3.2/docs/cn/TcpClient.md new file mode 100644 index 0000000..18a2aa9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/TcpClient.md @@ -0,0 +1,63 @@ +TCP 客户端类 + +```c++ + +class TcpClient { + + // 返回所在的事件循环 + const EventLoopPtr& loop(); + + // 创建套接字 + int createsocket(int remote_port, const char* remote_host = "127.0.0.1"); + int createsocket(struct sockaddr* remote_addr); + + // 绑定端口 + int bind(int local_port, const char* local_host = "0.0.0.0"); + int bind(struct sockaddr* local_addr); + + // 关闭套接字 + void closesocket(); + + // 开始运行 + void start(bool wait_threads_started = true); + + // 停止运行 + void stop(bool wait_threads_stopped = true); + + // 是否已连接 + bool isConnected(); + + // 发送 + int send(const void* data, int size); + int send(Buffer* buf); + int send(const std::string& str); + + // 设置SSL/TLS加密通信 + int withTLS(hssl_ctx_opt_t* opt = NULL); + + // 设置连接超时 + void setConnectTimeout(int ms); + + // 设置重连 + void setReconnect(reconn_setting_t* setting); + + // 是否是重连 + bool isReconnect(); + + // 设置拆包规则 + void setUnpack(unpack_setting_t* setting); + + // 连接状态回调 + std::function onConnection; + + // 消息回调 + std::function onMessage; + + // 写完成回调 + std::function onWriteComplete; + +}; + +``` + +测试代码见 [evpp/TcpClient_test.cpp](../../evpp/TcpClient_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/TcpServer.md b/external/libhv/libhv-1.3.2/docs/cn/TcpServer.md new file mode 100644 index 0000000..ec0932a --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/TcpServer.md @@ -0,0 +1,60 @@ +TCP 服务端类 + +```c++ + +class TcpServer { + + // 返回索引的事件循环 + EventLoopPtr loop(int idx = -1); + + // 创建套接字 + int createsocket(int port, const char* host = "0.0.0.0"); + + // 关闭套接字 + void closesocket(); + + // 设置最大连接数 + void setMaxConnectionNum(uint32_t num); + + // 设置负载均衡策略 + void setLoadBalance(load_balance_e lb); + + // 设置线程数 + void setThreadNum(int num); + + // 开始运行 + void start(bool wait_threads_started = true); + + // 停止运行 + void stop(bool wait_threads_stopped = true); + + // 设置SSL/TLS加密通信 + int withTLS(hssl_ctx_opt_t* opt = NULL); + + // 设置拆包规则 + void setUnpack(unpack_setting_t* setting); + + // 返回当前连接数 + size_t connectionNum(); + + // 遍历连接 + int foreachChannel(std::function fn); + + // 广播消息 + int broadcast(const void* data, int size); + int broadcast(const std::string& str); + + // 连接到来/断开回调 + std::function onConnection; + + // 消息回调 + std::function onMessage; + + // 写完成回调 + std::function onWriteComplete; + +}; + +``` + +测试代码见 [evpp/TcpServer_test.cpp](../../evpp/TcpServer_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/UdpClient.md b/external/libhv/libhv-1.3.2/docs/cn/UdpClient.md new file mode 100644 index 0000000..1544986 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/UdpClient.md @@ -0,0 +1,42 @@ +UDP 客户端类 + +```c++ + +class UdpClient { + + // 返回所在的事件循环 + const EventLoopPtr& loop(); + + // 创建套接字 + int createsocket(int remote_port, const char* remote_host = "127.0.0.1"); + + // 绑定端口 + int bind(int local_port, const char* local_host = "0.0.0.0"); + + // 关闭套接字 + void closesocket(); + + // 开始运行 + void start(bool wait_threads_started = true); + + // 停止运行 + void stop(bool wait_threads_stopped = true); + + // 发送 + int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL); + int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL); + int sendto(const std::string& str, struct sockaddr* peeraddr = NULL); + + // 设置KCP + void setKcp(kcp_setting_t* setting); + + // 消息回调 + std::function onMessage; + + // 写完成回调 + std::function onWriteComplete; +}; + +``` + +测试代码见 [evpp/UdpClient_test.cpp](../../evpp/UdpClient_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/UdpServer.md b/external/libhv/libhv-1.3.2/docs/cn/UdpServer.md new file mode 100644 index 0000000..cf4d3c6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/UdpServer.md @@ -0,0 +1,39 @@ +UDP 服务端类 + +```c++ + +class UdpServer { + + // 返回所在的事件循环 + const EventLoopPtr& loop(); + + // 创建套接字 + int createsocket(int port, const char* host = "0.0.0.0"); + + // 关闭套接字 + void closesocket(); + + // 开始运行 + void start(bool wait_threads_started = true); + + // 停止运行 + void stop(bool wait_threads_stopped = true); + + // 发送 + int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL); + int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL); + int sendto(const std::string& str, struct sockaddr* peeraddr = NULL); + + // 设置KCP + void setKcp(kcp_setting_t* setting); + + // 消息回调 + std::function onMessage; + + // 写完成回调 + std::function onWriteComplete; +}; + +``` + +测试代码见 [evpp/UdpServer_test.cpp](../../evpp/UdpServer_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/WebSocketClient.md b/external/libhv/libhv-1.3.2/docs/cn/WebSocketClient.md new file mode 100644 index 0000000..e015779 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/WebSocketClient.md @@ -0,0 +1,37 @@ +WebSocket 客户端类 + +```c++ + +class WebSocketClient { + + // 打开回调 + std::function onopen; + // 关闭回调 + std::function onclose; + // 消息回调 + std::function onmessage; + + // 打开 + int open(const char* url, const http_headers& headers = DefaultHeaders); + + // 关闭 + int close(); + + // 发送 + int send(const std::string& msg); + int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY); + + // 设置心跳间隔 + void setPingInterval(int ms); + + // 设置WebSocket握手阶段的HTTP请求 + void setHttpRequest(const HttpRequestPtr& req); + + // 获取WebSocket握手阶段的HTTP响应 + const HttpResponsePtr& getHttpResponse(); + +}; + +``` + +测试代码见 [examples/websocket_client_test.cpp](../../examples/websocket_client_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/WebSocketServer.md b/external/libhv/libhv-1.3.2/docs/cn/WebSocketServer.md new file mode 100644 index 0000000..0cd4f14 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/WebSocketServer.md @@ -0,0 +1,30 @@ +WebSocket 服务端类 + +```c++ + +// WebSocketServer 继承自 HttpServer +class WebSocketServer : public HttpServer { + + // 注册WebSocket业务类 + void registerWebSocketService(WebSocketService* service); + +}; + +// WebSocket业务类 +struct WebSocketService { + // 打开回调 + std::function onopen; + + // 消息回调 + std::function onmessage; + + // 关闭回调 + std::function onclose; + + // 心跳间隔 + int ping_interval; +}; + +``` + +测试代码见 [examples/websocket_server_test.cpp](../../examples/websocket_server_test.cpp) diff --git a/external/libhv/libhv-1.3.2/docs/cn/hbase.md b/external/libhv/libhv-1.3.2/docs/cn/hbase.md new file mode 100644 index 0000000..ec48809 --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/hbase.md @@ -0,0 +1,111 @@ +一些基础函数 + +```c + +/* hv内存分配/释放函数 */ +void* hv_malloc(size_t size); +void* hv_realloc(void* oldptr, size_t newsize, size_t oldsize); +void* hv_calloc(size_t nmemb, size_t size); +void* hv_zalloc(size_t size); +void hv_free(void* ptr); + +// 使用hv分配内存次数 +long hv_alloc_cnt(); + +// 使用hv释放内存次数 +long hv_free_cnt(); + +/* 字符串操作 */ +// 字符串转大写 +char* hv_strupper(char* str); +// 字符串转小写 +char* hv_strlower(char* str); +// 字符串翻转 +char* hv_strreverse(char* str); + +// 判断字符串是否以xxx开头 +bool hv_strstartswith(const char* str, const char* start); + +// 判断字符串是否以xxx结尾 +bool hv_strendswith(const char* str, const char* end); + +// 判断字符串是否包含xxx +bool hv_strcontains(const char* str, const char* sub); + +// 安全的strncpy +char* hv_strncpy(char* dest, const char* src, size_t n); + +// 安全的strncat +char* hv_strncat(char* dest, const char* src, size_t n); + +// 字符查找 +char* hv_strnchr(const char* s, char c, size_t n); + +// 查找最后一个点(通常用于提取文件后缀) +#define hv_strrchr_dot(str) strrchr(str, '.') + +// 查找最后的路径(通常用于分离目录和文件) +char* hv_strrchr_dir(const char* filepath); + +// 获取文件名(利用了上面的strrchr_dir) +const char* hv_basename(const char* filepath); + +// 获取文件后缀(利用了上面的strrchr_dot) +const char* hv_suffixname(const char* filename); + +/* 文件&目录 */ +// mkdir -p: 创建目录 +int hv_mkdir_p(const char* dir); +// rmdir -p: 删除目录 +int hv_rmdir_p(const char* dir); + +// 判断路径是否存在 +bool hv_exists(const char* path); + +// 判断是否是目录 +bool hv_isdir(const char* path); + +// 判断是否是文件 +bool hv_isfile(const char* path); + +// 判断是否是链接 +bool hv_islink(const char* path); + +// 获取文件大小 +size_t hv_filesize(const char* filepath); + +// 获取可执行文件绝对路径,例如/usr/local/bin/httpd +char* get_executable_path(char* buf, int size); + +// 获取可执行文件所在目录,例如/usr/local/bin +char* get_executable_dir(char* buf, int size); + +// 获取可执行文件名,例如httpd +char* get_executable_file(char* buf, int size); + +// 获取运行目录,例如/home/www/html +char* get_run_dir(char* buf, int size); + +// 返回一个随机数 +int hv_rand(int min, int max); + +// 返回一个随机字符串 +char* hv_random_string(char *buf, int len); + +// 1 y on yes true enable返回true(通常用于配置文件) +bool hv_getboolean(const char* str); + +// 解析size字符串 +// 1T2G3M4K5B => ?B +size_t hv_parse_size(const char* str); + +// 解析时间字符串 +// 1w2d3h4m5s => ?s +time_t hv_parse_time(const char* str); + +// 解析url字符串 +int hv_parse_url(hurl_t* stURL, const char* strURL); + +``` + +单元测试代码见 [unittest/hbase_test.c](../../unittest/hbase_test.c) diff --git a/external/libhv/libhv-1.3.2/docs/cn/hlog.md b/external/libhv/libhv-1.3.2/docs/cn/hlog.md new file mode 100644 index 0000000..63cb77d --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/hlog.md @@ -0,0 +1,111 @@ +日志 + +```c + +// 标准输出日志 +void stdout_logger(int loglevel, const char* buf, int len); + +// 标准错误日志 +void stderr_logger(int loglevel, const char* buf, int len); + +// 文件日志 +void file_logger(int loglevel, const char* buf, int len); + +// 网络日志(定义在event/nlog.h头文件里) +// void network_logger(int loglevel, const char* buf, int len); + +// 创建日志器 +logger_t* logger_create(); + +// 销毁日志器 +void logger_destroy(logger_t* logger); + +// 设置日志处理器 +void logger_set_handler(logger_t* logger, logger_handler fn); + +// 设置日志等级 +void logger_set_level(logger_t* logger, int level); +// level = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] +void logger_set_level_by_str(logger_t* logger, const char* level); + +/* + * 设置日志格式 + * format = "%y-%m-%d %H:%M:%S.%z %L %s" + * message = "2020-01-02 03:04:05.067 DEBUG message" + * %y year + * %m month + * %d day + * %H hour + * %M min + * %S sec + * %z ms + * %Z us + * %l First character of level + * %L All characters of level + * %s message + * %% % + */ +void logger_set_format(logger_t* logger, const char* format); + +// 设置日志缓存大小 +void logger_set_max_bufsize(logger_t* logger, unsigned int bufsize); + +// 启用日志颜色 +void logger_enable_color(logger_t* logger, int on); + +// 日志打印 +int logger_print(logger_t* logger, int level, const char* fmt, ...); + +// 设置日志文件 +void logger_set_file(logger_t* logger, const char* filepath); + +// 设置日志文件大小 +void logger_set_max_filesize(logger_t* logger, unsigned long long filesize); +// 16, 16M, 16MB +void logger_set_max_filesize_by_str(logger_t* logger, const char* filesize); + +// 设置日志文件保留天数 +void logger_set_remain_days(logger_t* logger, int days); + +// 启用每次写日志文件立即刷新到磁盘(即每次都调用fsync,会增加IO耗时,影响性能) +void logger_enable_fsync(logger_t* logger, int on); + +// 刷新缓存到磁盘(如对日志文件实时性有必要的,可使用定时器定时刷新到磁盘) +void logger_fsync(logger_t* logger); + +// 获取当前日志文件路径 +const char* logger_get_cur_file(logger_t* logger); + +// hlog: 默认的日志器 +logger_t* hv_default_logger(); + +// 销毁默认的日志器 +void hv_destroy_default_logger(void); + +// 对默认日志器hlog的一些便利操作宏 +#define hlog hv_default_logger() +#define hlog_destory() hv_destroy_default_logger() +/* 禁用hv的默认日志 */ +#define hlog_disable() logger_set_level(hlog, LOG_LEVEL_SILENT) +#define hlog_set_file(filepath) logger_set_file(hlog, filepath) +#define hlog_set_level(level) logger_set_level(hlog, level) +#define hlog_set_level_by_str(level) logger_set_level_by_str(hlog, level) +#define hlog_set_handler(fn) logger_set_handler(hlog, fn) +#define hlog_set_format(format) logger_set_format(hlog, format) +#define hlog_set_max_filesize(filesize) logger_set_max_filesize(hlog, filesize) +#define hlog_set_max_filesize_by_str(filesize) logger_set_max_filesize_by_str(hlog, filesize) +#define hlog_set_remain_days(days) logger_set_remain_days(hlog, days) +#define hlog_enable_fsync() logger_enable_fsync(hlog, 1) +#define hlog_disable_fsync() logger_enable_fsync(hlog, 0) +#define hlog_fsync() logger_fsync(hlog) +#define hlog_get_cur_file() logger_get_cur_file(hlog) + +#define hlogd(fmt, ...) logger_print(hlog, LOG_LEVEL_DEBUG, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogi(fmt, ...) logger_print(hlog, LOG_LEVEL_INFO, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogw(fmt, ...) logger_print(hlog, LOG_LEVEL_WARN, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hloge(fmt, ...) logger_print(hlog, LOG_LEVEL_ERROR, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) +#define hlogf(fmt, ...) logger_print(hlog, LOG_LEVEL_FATAL, fmt " [%s:%d:%s]\n", ## __VA_ARGS__, __FILENAME__, __LINE__, __FUNCTION__) + +``` + +测试代码见 [examples/hloop_test.c](../../examples/hloop_test.c) diff --git a/external/libhv/libhv-1.3.2/docs/cn/hloop.md b/external/libhv/libhv-1.3.2/docs/cn/hloop.md new file mode 100644 index 0000000..ebaf84a --- /dev/null +++ b/external/libhv/libhv-1.3.2/docs/cn/hloop.md @@ -0,0 +1,636 @@ +事件循环和IO多路复用机制介绍 + +事件循环是`libevent、libev、libuv、libhv`这类网络库里最核心的概念,即在事件循环里处理IO读写事件、定时器事件、自定义事件等各种事件;
+IO多路复用即在一个IO线程监听多个fd,如最早期的`select`、后来的`poll`,`linux的epoll`、`windows的iocp`、`bsd的kqueue`、`solaris的port`等,都属于IO多路复用机制。
+非阻塞NIO搭配IO多路复用机制就是高并发的钥匙。
+`libhv`下的`event`模块正是封装了多种平台的IO多路复用机制,提供了统一的事件接口,是`libhv`的核心模块。
+ +`hloop.h`: 事件循环模块对外头文件。
+ +```c + +// 事件结构体 +struct hevent_s { + hloop_t* loop; // 事件所属循环 + hevent_type_e event_type; // 事件类型 + uint64_t event_id; // 事件ID + hevent_cb cb; // 事件回调 + void* userdata; // 用户数据 + void* privdata; // 私有数据 + struct hevent_s* pending_next; // 指向下一个事件,用于实现事件队列 + int priority; // 事件优先级 +}; + +// 设置事件ID +#define hevent_set_id(ev, id) ((hevent_t*)(ev))->event_id = id +// 设置事件回调 +#define hevent_set_cb(ev, cb) ((hevent_t*)(ev))->cb = cb +// 设置事件优先级 +#define hevent_set_priority(ev, prio) ((hevent_t*)(ev))->priority = prio +// 设置事件用户数据 +#define hevent_set_userdata(ev, udata) ((hevent_t*)(ev))->userdata = (void*)udata + +// 获取事件所属循环 +#define hevent_loop(ev) (((hevent_t*)(ev))->loop) +// 获取事件类型 +#define hevent_type(ev) (((hevent_t*)(ev))->event_type) +// 获取事件ID +#define hevent_id(ev) (((hevent_t*)(ev))->event_id) +// 获取事件回调 +#define hevent_cb(ev) (((hevent_t*)(ev))->cb) +// 获取事件优先级 +#define hevent_priority(ev) (((hevent_t*)(ev))->priority) +// 获取事件用户数据 +#define hevent_userdata(ev) (((hevent_t*)(ev))->userdata) + +// hidle_t、htimer_t、hio_t皆是继承自hevent_t,继承上面的数据成员和函数方法 + +// 新建事件循环 +hloop_t* hloop_new(int flags DEFAULT(HLOOP_FLAG_AUTO_FREE)); + +// 释放事件循环 +void hloop_free(hloop_t** pp); + +// 运行事件循环 +int hloop_run(hloop_t* loop); + +// 停止事件循环 +int hloop_stop(hloop_t* loop); + +// 暂停事件循环 +int hloop_pause(hloop_t* loop); + +// 继续事件循环 +int hloop_resume(hloop_t* loop); + +// 唤醒事件循环 +int hloop_wakeup(hloop_t* loop); + +// 返回事件循环状态 +hloop_status_e hloop_status(hloop_t* loop); + +// 更新事件循环里的时间 +void hloop_update_time(hloop_t* loop); + +// 返回事件循环里记录的时间 +uint64_t hloop_now(hloop_t* loop); // s +uint64_t hloop_now_ms(hloop_t* loop); // ms +uint64_t hloop_now_us(hloop_t* loop); // us + +// 返回事件循环所在进程ID +long hloop_pid(hloop_t* loop); + +// 返回事件循环所在线程ID +long hloop_tid(hloop_t* loop); + +// 返回事件循环的循环次数 +uint64_t hloop_count(hloop_t* loop); + +// 返回事件循环里激活的IO事件数量 +uint32_t hloop_nios(hloop_t* loop); + +// 返回事件循环里激活的定时器事件数量 +uint32_t hloop_ntimers(hloop_t* loop); + +// 返回事件循环里激活的空闲事件数量 +uint32_t hloop_nidles(hloop_t* loop); + +// 返回事件循环里激活的事件数量 +uint32_t hloop_nactives(hloop_t* loop); + +// 设置事件循环的用户数据 +void hloop_set_userdata(hloop_t* loop, void* userdata); + +// 获取事件循环的用户数据 +void* hloop_userdata(hloop_t* loop); + +// 投递事件 +void hloop_post_event(hloop_t* loop, hevent_t* ev); + +// 添加空闲事件 +hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat DEFAULT(INFINITE)); + +// 删除空闲事件 +void hidle_del(hidle_t* idle); + +// 添加超时定时器 +htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat DEFAULT(INFINITE)); + +// 添加时间定时器 +htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, + int8_t minute DEFAULT(0), int8_t hour DEFAULT(-1), int8_t day DEFAULT(-1), + int8_t week DEFAULT(-1), int8_t month DEFAULT(-1), uint32_t repeat DEFAULT(INFINITE)); + +// 删除定时器 +void htimer_del(htimer_t* timer); + +// 重置定时器 +void htimer_reset(htimer_t* timer, uint32_t timeout_ms DEFAULT(0)); + +// 返回IO多路复用引擎 (select、poll、epoll、etc.) +const char* hio_engine(); + +// 获取IO对象 +hio_t* hio_get(hloop_t* loop, int fd); + +// 添加IO读写事件 +int hio_add(hio_t* io, hio_cb cb, int events DEFAULT(HV_READ)); + +// 删除IO读写事件 +int hio_del(hio_t* io, int events DEFAULT(HV_RDWR)); + +// 将IO对象从当前所属事件循环中剥离 +void hio_detach(/*hloop_t* loop,*/ hio_t* io); + +// 将IO对象关联到新的事件循环 +void hio_attach(hloop_t* loop, hio_t* io); + +// hio_detach 和 hio_attach 的示例代码见 examples/multi-thread/one-acceptor-multi-workers.c +/* +void new_conn_event(hevent_t* ev) { + hloop_t* loop = ev->loop; + hio_t* io = (hio_t*)hevent_userdata(ev); + // 关联到新的worker事件循环 + hio_attach(loop, io); +} + +void on_accpet(hio_t* io) { + // 从acceptor所在事件循环中剥离 + hio_detach(io); + + // 将新的连接按照负载均衡策略分发到worker线程 + hloop_t* worker_loop = get_one_loop(); + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.loop = worker_loop; + ev.cb = new_conn_event; + ev.userdata = io; + hloop_post_event(worker_loop, &ev); +} +*/ + +// 判断fd是否存在于事件循环 +bool hio_exists(hloop_t* loop, int fd); + +// 返回一个唯一标示ID +uint32_t hio_id (hio_t* io); + +// 返回文件描述符 +int hio_fd (hio_t* io); + +// 返回错误码 +int hio_error (hio_t* io); + +// 返回添加的事件 +int hio_events (hio_t* io); + +// 获取返回的事件 +int hio_revents (hio_t* io); + +// 返回IO类型 +hio_type_e hio_type (hio_t* io); + +// 返回本地地址 +struct sockaddr* hio_localaddr(hio_t* io); + +// 返回对端地址 +struct sockaddr* hio_peeraddr (hio_t* io); + +// 设置上下文 +void hio_set_context(hio_t* io, void* ctx); + +// 获取上下文 +void* hio_context(hio_t* io); + +// 是否已打开 +bool hio_is_opened(hio_t* io); + +// 是否已连接 +bool hio_is_connected(hio_t* io); + +// 是否已关闭 +bool hio_is_closed(hio_t* io); + +// 设置读缓存 +void hio_set_readbuf(hio_t* io, void* buf, size_t len); + +// 获取读缓存 +hio_readbuf_t* hio_get_readbuf(hio_t* io); + +// 设置最大读缓存 +void hio_set_max_read_bufsize (hio_t* io, uint32_t size); + +// 设置最大写缓存 +void hio_set_max_write_bufsize(hio_t* io, uint32_t size); + +// 获取当前写缓存大小 +size_t hio_write_bufsize(hio_t* io); + +// 判断是否写完成 +#define hio_write_is_complete(io) (hio_write_bufsize(io) == 0) + +// 获取最后读的时间 +uint64_t hio_last_read_time(hio_t* io); // ms + +// 获取最后写的时间 +uint64_t hio_last_write_time(hio_t* io); // ms + +// 设置accept回调 +void hio_setcb_accept (hio_t* io, haccept_cb accept_cb); +// 设置连接回调 +void hio_setcb_connect (hio_t* io, hconnect_cb connect_cb); +// 设置读回调 +void hio_setcb_read (hio_t* io, hread_cb read_cb); +// 设置写回调 +void hio_setcb_write (hio_t* io, hwrite_cb write_cb); +// 设置关闭回调 +void hio_setcb_close (hio_t* io, hclose_cb close_cb); + +// 获取accept回调 +haccept_cb hio_getcb_accept(hio_t* io); +// 获取连接回调 +hconnect_cb hio_getcb_connect(hio_t* io); +// 获取读回调 +hread_cb hio_getcb_read(hio_t* io); +// 获取写回调 +hwrite_cb hio_getcb_write(hio_t* io); +// 获取关闭回调 +hclose_cb hio_getcb_close(hio_t* io); + +// 开启SSL/TLS加密通信 +int hio_enable_ssl(hio_t* io); +// 是否SSL/TLS加密通信 +bool hio_is_ssl(hio_t* io); +// 设置SSL +int hio_set_ssl (hio_t* io, hssl_t ssl); +// 设置SSL_CTX +int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx); +// 新建SSL_CTX +int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); +// 获取SSL +hssl_t hio_get_ssl(hio_t* io); +// 获取SSL_CTX +hssl_ctx_t hio_get_ssl_ctx(hio_t* io); +// 设置主机名 +int hio_set_hostname(hio_t* io, const char* hostname); +// 获取主机名 +const char* hio_get_hostname(hio_t* io); + +// 设置连接超时 +void hio_set_connect_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CONNECT_TIMEOUT)); +// 设置关闭超时 (说明:非阻塞写队列非空时,需要等待写完成再关闭) +void hio_set_close_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CLOSE_TIMEOUT)); +// 设置读超时 (一段时间没有数据到来便自动关闭连接) +void hio_set_read_timeout(hio_t* io, int timeout_ms); +// 设置写超时 (一段时间没有数据发送便自动关闭连接) +void hio_set_write_timeout(hio_t* io, int timeout_ms); +// 设置keepalive超时 (一段时间没有数据收发便自动关闭连接) +void hio_set_keepalive_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_KEEPALIVE_TIMEOUT)); + +// 设置心跳 (定时发送心跳包) +typedef void (*hio_send_heartbeat_fn)(hio_t* io); +void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn); + +// 接收连接 +// hio_add(io, HV_READ) => accept => haccept_cb +int hio_accept (hio_t* io); + +// 连接 +// connect => hio_add(io, HV_WRITE) => hconnect_cb +int hio_connect(hio_t* io); + +// 读 +// hio_add(io, HV_READ) => read => hread_cb +int hio_read (hio_t* io); + +// 开始读 +#define hio_read_start(io) hio_read(io) + +// 停止读 +#define hio_read_stop(io) hio_del(io, HV_READ) + +// 读一次 +// hio_read_start => hread_cb => hio_read_stop +int hio_read_once (hio_t* io); + +// 读取直到指定长度 +// hio_read_once => hread_cb(len) +int hio_read_until_length(hio_t* io, unsigned int len); + +// 读取直到遇到分隔符 +// hio_read_once => hread_cb(...delim) +int hio_read_until_delim (hio_t* io, unsigned char delim); + +// 读取一行 +#define hio_readline(io) hio_read_until_delim(io, '\n') + +// 读取字符串 +#define hio_readstring(io) hio_read_until_delim(io, '\0') + +// 读取N个字节 +#define hio_readbytes(io, len) hio_read_until_length(io, len) +#define hio_read_until(io, len) hio_read_until_length(io, len) + +// 写 +// hio_try_write => hio_add(io, HV_WRITE) => write => hwrite_cb +int hio_write (hio_t* io, const void* buf, size_t len); + +// 关闭 +// hio_del(io, HV_RDWR) => close => hclose_cb +int hio_close (hio_t* io); + +// 异步关闭 (投递一个close事件) +// NOTE: hloop_post_event(hio_close_event) +int hio_close_async(hio_t* io); + +//------------------高等级的接口------------------------------------------- +// 读 +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +hio_t* hread (hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb); +// 写 +// hio_get -> hio_setcb_write -> hio_write +hio_t* hwrite (hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); +// 关闭 +// hio_get -> hio_close +void hclose (hloop_t* loop, int fd); + +// tcp +// 接收连接 +// hio_get -> hio_setcb_accept -> hio_accept +hio_t* haccept (hloop_t* loop, int listenfd, haccept_cb accept_cb); +// 连接 +// hio_get -> hio_setcb_connect -> hio_connect +hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb); +// 接收 +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb); +// 发送 +// hio_get -> hio_setcb_write -> hio_write +hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); + +// udp +// 设置IO类型 +void hio_set_type(hio_t* io, hio_type_e type); +// 设置本地地址 +void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen); +// 设置对端地址 +void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen); +// 接收 +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb); +// 发送 +// hio_get -> hio_setcb_write -> hio_write +hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); + +//-----------------顶层的接口--------------------------------------------- +// 创建socket套接字,返回IO对象 +// @hio_create_socket: socket -> bind -> listen +// sockaddr_set_ipport -> socket -> hio_get(loop, sockfd) -> +// side == HIO_SERVER_SIDE ? bind -> +// type & HIO_TYPE_SOCK_STREAM ? listen -> +hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, + hio_type_e type DEFAULT(HIO_TYPE_TCP), + hio_side_e side DEFAULT(HIO_SERVER_SIDE)); + +// @tcp_server: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept +// 创建TCP服务,示例代码见 examples/tcp_echo_server.c +hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); + +// @tcp_client: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect +// 创建TCP客户端,示例代码见 examples/nc.c +hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); + +// @ssl_server: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept +// 创建SSL服务端,示例代码见 examples/tcp_echo_server.c => #define TEST_SSL 1 +hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); + +// @ssl_client: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect +// 创建SSL客户端,示例代码见 examples/nc.c => #define TEST_SSL 1 +hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); + +// @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE) +// 创建UDP服务端,示例代码见 examples/udp_echo_server.c +hio_t* hloop_create_udp_server (hloop_t* loop, const char* host, int port); + +// @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE) +// 创建UDP客户端,示例代码见 examples/nc.c +hio_t* hloop_create_udp_client (hloop_t* loop, const char* host, int port); + +//-----------------转发--------------------------------------------- +// hio_read(io) +// hio_read(io->upstream_io) +void hio_read_upstream(hio_t* io); +// on_write(io) -> hio_write_is_complete(io) -> hio_read(io->upstream_io) +void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes); +// hio_write(io->upstream_io, buf, bytes) +void hio_write_upstream(hio_t* io, void* buf, int bytes); +// hio_close(io->upstream_io) +void hio_close_upstream(hio_t* io); + +// io1->upstream_io = io2; +// io2->upstream_io = io1; +// 建立转发,示例代码见 examples/socks5_proxy_server.c +void hio_setup_upstream(hio_t* io1, hio_t* io2); + +// @return io->upstream_io +hio_t* hio_get_upstream(hio_t* io); + +// @tcp_upstream: hio_create_socket -> hio_setup_upstream -> hio_connect -> on_connect -> hio_read_upstream +// @return upstream_io +// 建立TCP转发,示例代码见 examples/tcp_proxy_server.c +hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl DEFAULT(0)); +// 建立SSL转发 +#define hio_setup_ssl_upstream(io, host, port) hio_setup_tcp_upstream(io, host, port, 1) + +// @udp_upstream: hio_create_socket -> hio_setup_upstream -> hio_read_upstream +// @return upstream_io +// 建立UDP转发,示例代码见 examples/udp_proxy_server.c +hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port); + +//-----------------拆包--------------------------------------------- +// 拆包模式 +typedef enum { + UNPACK_MODE_NONE = 0, + UNPACK_BY_FIXED_LENGTH = 1, // 固定长度拆包,不建议 + UNPACK_BY_DELIMITER = 2, // 根据分隔符拆包,适用于文本协议 + UNPACK_BY_LENGTH_FIELD = 3, // 根据头部长度字段拆包,适用于二进制协议 +} unpack_mode_e; + +// 拆包设置 +typedef struct unpack_setting_s { + unpack_mode_e mode; // 拆包模式 + unsigned int package_max_length; // 最大的包长 + union { + // UNPACK_BY_FIXED_LENGTH: 固定长度拆包设置 + struct { + unsigned int fixed_length; // 固定长度 + }; + // UNPACK_BY_DELIMITER: 分隔符拆包设置 + struct { + unsigned char delimiter[PACKAGE_MAX_DELIMITER_BYTES]; // 分隔符 + unsigned short delimiter_bytes; // 分隔符所占字节数 + }; + /* + * UNPACK_BY_LENGTH_FIELD: 头部长度字段拆包设置 + * + * 包长 = 头部长度 + 数据长度 + 调整长度 + * package_len = head_len + body_len + length_adjustment + * + * if (length_field_coding == ENCODE_BY_VARINT) head_len = body_offset + varint_bytes - length_field_bytes; + * else head_len = body_offset; + * + * 注意:头部长度字段的值仅代表数据长度,不包括头部本身长度, + * 如果你的头部长度字段代表总包长,那么应该将length_adjustment设置为负的头部长度 + * length_field stores body length, exclude head length, + * if length_field = head_len + body_len, then length_adjustment should be set to -head_len. + * + */ + struct { + unsigned short body_offset; // 到数据的偏移,通常等于头部长度 + unsigned short length_field_offset; // 长度字段偏移 + unsigned short length_field_bytes; // 长度字段所占字节数 + short length_adjustment; // 调整长度 + unpack_coding_e length_field_coding; // 长度字段编码方式 + }; + }; +} unpack_setting_t; + +/* + * 拆包示例代码见 examples/jsonrpc examples/protorpc + * + * 注意:多个IO对象的unpack_setting_t可能是一样的,所有hio_t里仅保存了unpack_setting_t的指针, + * unpack_setting_t的生命周期应该被调用者所保证,不应该使用局部变量。 + */ + +// 设置拆包 +void hio_set_unpack(hio_t* io, unpack_setting_t* setting); +// 取消拆包设置 +void hio_unset_unpack(hio_t* io); + +// 拆包设置示例: +/* + +// FTP协议通过\r\n分割符拆包 +unpack_setting_t ftp_unpack_setting; +memset(&ftp_unpack_setting, 0, sizeof(unpack_setting_t)); +ftp_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; +ftp_unpack_setting.mode = UNPACK_BY_DELIMITER; +ftp_unpack_setting.delimiter[0] = '\r'; +ftp_unpack_setting.delimiter[1] = '\n'; +ftp_unpack_setting.delimiter_bytes = 2; + +// MQTT协议通过头部长度字段拆包,头部长度字段使用了varint编码 +unpack_setting_t mqtt_unpack_setting = { + .mode = UNPACK_BY_LENGTH_FIELD, + .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, + .body_offset = 2, + .length_field_offset = 1, + .length_field_bytes = 1, + .length_field_coding = ENCODE_BY_VARINT, +}; + +*/ + +//-----------------重连---------------------------------------- +// 重连设置 +typedef struct reconn_setting_s { + uint32_t min_delay; // ms 重连最小延时 + uint32_t max_delay; // ms 重连最大延时 + uint32_t cur_delay; // ms 当前延时 + /* + * @delay_policy: 延时策略 + * 0: fixed 固定延时 + * min_delay=3s => 3,3,3... + * 1: linear 线性增长延时 + * min_delay=3s max_delay=10s => 3,6,9,10,10... + * other: exponential 指数增长延时 + * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60... + */ + uint32_t delay_policy; // 延时策略 + uint32_t max_retry_cnt; // 最大重试次数 + uint32_t cur_retry_cnt; // 当前重试次数 +} reconn_setting_t; + +// 重连设置初始化 +void reconn_setting_init(reconn_setting_t* reconn); + +// 重连设置重置 +void reconn_setting_reset(reconn_setting_t* reconn); + +// 增加重试次数并判断是否未超过最大重试次数 +bool reconn_setting_can_retry(reconn_setting_t* reconn); + +// 计算当前重连延时 +uint32_t reconn_setting_calc_delay(reconn_setting_t* reconn); + +//-----------------负载均衡------------------------------------- +// 负载均衡策略枚举 +typedef enum { + LB_RoundRobin, // 轮询 + LB_Random, // 随机 + LB_LeastConnections,// 最少连接数 + LB_IpHash, // IP hash + LB_UrlHash, // URL hash +} load_balance_e; + +//-----------------可靠UDP--------------------------------------------- +// 关闭可靠UDP +int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr DEFAULT(NULL)); + +// KCP设置 +typedef struct kcp_setting_s { + // ikcp_create(conv, ...) + unsigned int conv; + // ikcp_nodelay(kcp, nodelay, interval, fastresend, nocwnd) + int nodelay; + int interval; + int fastresend; + int nocwnd; + // ikcp_wndsize(kcp, sndwnd, rcvwnd) + int sndwnd; + int rcvwnd; + // ikcp_setmtu(kcp, mtu) + int mtu; + // ikcp_update + int update_interval; +} kcp_setting_t; + +// KCP 正常模式 +HV_INLINE void kcp_setting_init_with_normal_mode(kcp_setting_t* setting); + +// KCP fast模式 +void kcp_setting_init_with_fast_mode(kcp_setting_t* setting); + +// KCP fast2模式 +void kcp_setting_init_with_fast2_mode(kcp_setting_t* setting); + +// KCP fast3模式 +void kcp_setting_init_with_fast3_mode(kcp_setting_t* setting); + +// 设置KCP,示例代码见 examples/udp_echo_server.c => #define TEST_KCP 1 +int hio_set_kcp(hio_t* io, kcp_setting_t* setting DEFAULT(NULL)); + +``` + +示例代码: + +- 事件循环: [examples/hloop_test.c](../../examples/hloop_test.c) +- 定时器: [examples/htimer_test.c](../../examples/htimer_test.c) +- TCP回显服务: [examples/tcp_echo_server.c](../../examples/tcp_echo_server.c) +- TCP聊天服务: [examples/tcp_chat_server.c](../../examples/tcp_chat_server.c) +- TCP代理服务: [examples/tcp_proxy_server.c](../../examples/tcp_proxy_server.c) +- TCP客户端: [examples/tcp_client_test.c](../../examples/tcp_client_test.c) +- UDP回显服务: [examples/udp_echo_server.c](../../examples/udp_echo_server.c) +- UDP代理服务: [examples/udp_proxy_server.c](../../examples/udp_proxy_server.c) +- 网络客户端: [examples/nc](../../examples/nc.c) +- SOCKS5代理服务: [examples/socks5_proxy_server.c](../../examples/socks5_proxy_server.c) +- HTTP服务: [examples/tinyhttpd.c](../../examples/tinyhttpd.c) +- HTTP代理服务: [examples/tinyproxyd.c](../../examples/tinyproxyd.c) +- jsonRPC示例: [examples/jsonrpc](../../examples/jsonrpc) +- protobufRPC示例: [examples/protorpc](../../examples/protorpc) + +多进程/多线程模式示例代码: + +- 多accept进程模式: [examples/multi-thread/multi-acceptor-processes.c](../../examples/multi-thread/multi-acceptor-processes.c) +- 多accept线程模式: [examples/multi-thread/multi-acceptor-threads.c](../../examples/multi-thread/multi-acceptor-threads.c) +- 一个accept线程+多worker线程: [examples/multi-thread/one-acceptor-multi-workers.c](../../examples/multi-thread/one-acceptor-multi-workers.c) diff --git a/external/libhv/libhv-1.3.2/echo-servers/asio_echo.cpp b/external/libhv/libhv-1.3.2/echo-servers/asio_echo.cpp new file mode 100644 index 0000000..8a435f5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/asio_echo.cpp @@ -0,0 +1,105 @@ +// +// async_tcp_echo_server.cpp +// ~~~~~~~~~~~~~~~~~~~~~~~~~ +// +// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) +// +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +#include +#include +#include +#include + +using boost::asio::ip::tcp; + +class session { +public: + session(boost::asio::io_service& io_service) : + socket_(io_service) { + } + + tcp::socket& socket() { + return socket_; + } + + void start() { + socket_.async_read_some(boost::asio::buffer(data_, max_length), + boost::bind(&session::handle_read, this, + boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); + } + + void handle_read(const boost::system::error_code& error, + size_t bytes_transferred) { + if (!error) { + boost::asio::async_write(socket_, boost::asio::buffer(data_, + bytes_transferred), boost::bind(&session::handle_write, + this, boost::asio::placeholders::error)); + } else { + delete this; + } + } + + void handle_write(const boost::system::error_code& error) { + if (!error) { + socket_.async_read_some(boost::asio::buffer(data_, max_length), + boost::bind(&session::handle_read, this, + boost::asio::placeholders::error, + boost::asio::placeholders::bytes_transferred)); + } else { + delete this; + } + } + +private: + tcp::socket socket_; + enum { + max_length = 1024 + }; + char data_[max_length]; +}; + +class server { +public: + server(boost::asio::io_service& io_service, short port) : + io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), + port)) { + session* new_session = new session(io_service_); + acceptor_.async_accept(new_session->socket(), boost::bind( + &server::handle_accept, this, new_session, + boost::asio::placeholders::error)); + } + + void handle_accept(session* new_session, + const boost::system::error_code& error) { + if (!error) { + new_session->start(); + new_session = new session(io_service_); + acceptor_.async_accept(new_session->socket(), boost::bind( + &server::handle_accept, this, new_session, + boost::asio::placeholders::error)); + } else { + delete new_session; + } + } + +private: + boost::asio::io_service& io_service_; + tcp::acceptor acceptor_; +}; + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + boost::asio::io_service io_service; + server s(io_service, port); + io_service.run(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/benchmark.sh b/external/libhv/libhv-1.3.2/echo-servers/benchmark.sh new file mode 100755 index 0000000..d5b1190 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/benchmark.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +host=127.0.0.1 +port=2000 +connections=100 +duration=10 +threads=2 +sendbytes=1024 + +while getopts 'h:p:c:d:t:' opt +do + case $opt in + h) host=$OPTARG;; + p) port=$OPTARG;; + c) connections=$OPTARG;; + d) duration=$OPTARG;; + t) threads=$OPTARG;; + *) exit -1;; + esac +done + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +cd ${SCRIPT_DIR}/.. + +killall_echo_servers() { + #sudo killall libevent_echo libev_echo libuv_echo libhv_echo asio_echo poco_echo muduo_echo + if [ $(ps aux | grep _echo | grep -v grep | wc -l) -gt 0 ]; then + ps aux | grep _echo | grep -v grep | awk '{print $2}' | xargs sudo kill -9 + fi +} + +export LD_LIBRARY_PATH=lib:$LD_LIBRARY_PATH + +killall_echo_servers + +sport=$port + +if [ -x bin/libevent_echo ]; then + let port++ + bin/libevent_echo $port & + echo "libevent running on port $port" +fi + +if [ -x bin/libev_echo ]; then + let port++ + bin/libev_echo $port & + echo "libev running on port $port" +fi + +if [ -x bin/libuv_echo ]; then + let port++ + bin/libuv_echo $port & + echo "libuv running on port $port" +fi + +if [ -x bin/libhv_echo ]; then + let port++ + bin/libhv_echo $port & + echo "libhv running on port $port" +fi + +if [ -x bin/asio_echo ]; then + let port++ + bin/asio_echo $port & + echo "asio running on port $port" +fi + +if [ -x bin/poco_echo ]; then + let port++ + bin/poco_echo $port & + echo "poco running on port $port" +fi + +if [ -x bin/muduo_echo ]; then + let port++ + bin/muduo_echo $port & + echo "muduo running on port $port" +fi + +sleep 1 + +for ((p=$sport+1; p<=$port; ++p)); do + echo -e "\n==============$p=====================================" + bin/pingpong_client -H $host -p $p -c $connections -d $duration -t $threads -b $sendbytes + sleep 1 +done + +killall_echo_servers diff --git a/external/libhv/libhv-1.3.2/echo-servers/build.sh b/external/libhv/libhv-1.3.2/echo-servers/build.sh new file mode 100755 index 0000000..be318f6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/build.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. + +# install libevent libev libuv asio poco +UNAME=$(uname -a) +case ${UNAME} in + *Ubuntu*|*Debian*) + sudo apt install libevent-dev libev-dev libuv1-dev libboost-dev libboost-system-dev libasio-dev libpoco-dev + ;; + *CentOS*) + sudo yum install libevent-devel libev-devel libuv-devel boost-devel asio-devel poco-devel + ;; + *Darwin*) + brew install libevent libev libuv boost asio poco + ;; + *) + echo 'please install libevent libev libuv boost asio poco' + ;; +esac + +# install muduo => https://github.com/chenshuo/muduo.git +TEST_MUDUO=false +if [ "$TEST_MUDUO" == "true" ]; then + cd ${ROOT_DIR}/.. + git clone https://github.com/chenshuo/muduo.git + cd muduo + mkdir build && cd build + cmake .. && make && sudo make install +fi + +# install libhv +cd ${ROOT_DIR} +make libhv && sudo make install && sudo ldconfig + +# build echo-servers +make echo-servers diff --git a/external/libhv/libhv-1.3.2/echo-servers/libev_echo.c b/external/libhv/libhv-1.3.2/echo-servers/libev_echo.c new file mode 100644 index 0000000..cb1295c --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/libev_echo.c @@ -0,0 +1,78 @@ +#include +#include +#include +#include + +#include +#include +#include + +#include "ev.h" + +#define RECV_BUFSIZE 8192 +static char recvbuf[RECV_BUFSIZE]; + +void do_recv(struct ev_loop *loop, struct ev_io *io, int revents) { + int nread, nsend; + nread = recv(io->fd, recvbuf, RECV_BUFSIZE, 0); + if (nread <= 0) { + goto error; + } + nsend = send(io->fd, recvbuf, nread, 0); + if (nsend != nread) { + goto error; + } + return; + +error: + ev_io_stop(loop, io); + close(io->fd); + free(io); +} + +void do_accept(struct ev_loop *loop, struct ev_io *listenio, int revents) { + struct sockaddr_in peeraddr; + socklen_t addrlen = sizeof(peeraddr); + int connfd = accept(listenio->fd, (struct sockaddr*)&peeraddr, &addrlen); + if (connfd <= 0) { + return; + } + + struct ev_io* io = (struct ev_io*)malloc(sizeof(struct ev_io)); + ev_io_init(io, do_recv, connfd, EV_READ); + ev_io_start(loop, io); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + struct sockaddr_in addr; + int addrlen = sizeof(addr); + memset(&addr, 0, addrlen); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + int listenfd = socket(AF_INET, SOCK_STREAM, 0); + if (listenfd < 0) { + return -20; + } + if (bind(listenfd, (struct sockaddr*)&addr, addrlen) < 0) { + return -30; + } + if (listen(listenfd, SOMAXCONN) < 0) { + return -40; + } + + struct ev_loop* loop = ev_loop_new(0); + + struct ev_io listenio; + ev_io_init(&listenio, do_accept, listenfd, EV_READ); + ev_io_start(loop, &listenio); + + ev_run(loop, 0); + ev_loop_destroy(loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/libevent_echo.c b/external/libhv/libhv-1.3.2/echo-servers/libevent_echo.c new file mode 100644 index 0000000..5c8e266 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/libevent_echo.c @@ -0,0 +1,61 @@ +#include +#include +#include + +#include "event2/event.h" +#include "event2/listener.h" +#include "event2/bufferevent.h" +#include "event2/buffer.h" + +//#define RECV_BUFSIZE 8192 + +void error_cb(struct bufferevent* bev, short event, void* userdata) { + bufferevent_free(bev); +} + +void read_cb(struct bufferevent* bev, void* userdata) { + //static char recvbuf[RECV_BUFSIZE]; + //int nread = bufferevent_read(bev, &recvbuf, RECV_BUFSIZE); + //bufferevent_write(bev, recvbuf, nread); + struct evbuffer* buf = evbuffer_new(); + int ret = bufferevent_read_buffer(bev, buf); + if (ret == 0) { + bufferevent_write_buffer(bev, buf); + } + evbuffer_free(buf); +} + +void on_accept(struct evconnlistener* listener, evutil_socket_t connfd, struct sockaddr* peeraddr, int addrlen, void* userdata) { + struct event_base* loop = evconnlistener_get_base(listener); + struct bufferevent* bev = bufferevent_socket_new(loop, connfd, BEV_OPT_CLOSE_ON_FREE); + bufferevent_setcb(bev, read_cb, NULL, error_cb, NULL); + bufferevent_enable(bev, EV_READ|EV_WRITE|EV_PERSIST); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + struct event_base* loop = event_base_new(); + + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_port = htons(port); + struct evconnlistener* listener = evconnlistener_new_bind( + loop, on_accept, NULL, + LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, + -1, (struct sockaddr*)&addr, sizeof(addr)); + if (listener == NULL) { + return -20; + } + + event_base_dispatch(loop); + + evconnlistener_free(listener); + event_base_free(loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/libhv_echo.c b/external/libhv/libhv-1.3.2/echo-servers/libhv_echo.c new file mode 100644 index 0000000..8cfc153 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/libhv_echo.c @@ -0,0 +1,31 @@ +#include "hv/hloop.h" + +void on_close(hio_t* io) { +} + +void on_recv(hio_t* io, void* buf, int readbytes) { + hio_write(io, buf, readbytes); +} + +void on_accept(hio_t* io) { + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_read(io); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + hloop_t* loop = hloop_new(0); + hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); + if (listenio == NULL) { + return -20; + } + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/libuv_echo.c b/external/libhv/libhv-1.3.2/echo-servers/libuv_echo.c new file mode 100644 index 0000000..abc7d18 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/libuv_echo.c @@ -0,0 +1,75 @@ +#define _GNU_SOURCE 1 +#include +#include +#include + +#include "uv.h" + +typedef struct { + uv_write_t req; + uv_buf_t buf; +} uv_write_req_t; + +void alloc_cb(uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { + buf->base = (char*)malloc(suggested_size); + buf->len = suggested_size; +} + +void close_cb(uv_handle_t* handle) { + free(handle); +} + +void write_cb(uv_write_t* req, int status) { + uv_write_req_t* wr = (uv_write_req_t*)req; + free(wr->buf.base); + free(wr); +} + +void read_cb(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf) { + if (nread <= 0) { + uv_close((uv_handle_t*)stream, close_cb); + return; + } + uv_write_req_t* wr = (uv_write_req_t*)malloc(sizeof(uv_write_req_t)); + wr->buf.base = buf->base; + wr->buf.len = nread; + uv_write(&wr->req, stream, &wr->buf, 1, write_cb); +} + +void do_accept(uv_stream_t* server, int status) { + uv_tcp_t* tcp_stream = (uv_tcp_t*)malloc(sizeof(uv_tcp_t)); + uv_tcp_init(server->loop, tcp_stream); + uv_accept(server, (uv_stream_t*)tcp_stream); + uv_read_start((uv_stream_t*)tcp_stream, alloc_cb, read_cb); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + uv_loop_t loop; + uv_loop_init(&loop); + + struct sockaddr_in addr; + memset(&addr, 0, sizeof(addr)); + //addr.sin_family = AF_INET; + //addr.sin_port = htons(port); + uv_ip4_addr("0.0.0.0", port, &addr); + + uv_tcp_t tcp_server; + uv_tcp_init(&loop, &tcp_server); + int ret = uv_tcp_bind(&tcp_server, (struct sockaddr*)&addr, 0); + if (ret) { + return -20; + } + ret = uv_listen((uv_stream_t*)&tcp_server, SOMAXCONN, do_accept); + if (ret) { + return -30; + } + + uv_run(&loop, UV_RUN_DEFAULT); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/muduo_echo.cpp b/external/libhv/libhv-1.3.2/echo-servers/muduo_echo.cpp new file mode 100644 index 0000000..60e4402 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/muduo_echo.cpp @@ -0,0 +1,62 @@ +// @see muduo/examples/simple/echo +#include "muduo/base/Logging.h" +#include "muduo/net/EventLoop.h" +#include "muduo/net/InetAddress.h" +#include "muduo/net/TcpServer.h" + +using std::placeholders::_1; +using std::placeholders::_2; +using std::placeholders::_3; + +using muduo::Timestamp; + +using muduo::net::EventLoop; +using muduo::net::InetAddress; +using muduo::net::TcpServer; +using muduo::net::TcpConnectionPtr; +using muduo::net::Buffer; + +class EchoTcpServer { +public: + EchoTcpServer(EventLoop* loop, const InetAddress& addr) + : server_(loop, addr, "EchoTcpServer") + { + server_.setConnectionCallback(std::bind(&EchoTcpServer::onConnection, this, _1)); + server_.setMessageCallback(std::bind(&EchoTcpServer::onMessage, this, _1, _2, _3)); + } + + void start() { + server_.start(); + } + +private: + void onConnection(const TcpConnectionPtr& conn) { + } + + void onMessage(const TcpConnectionPtr& conn, + Buffer* buf, Timestamp time) { + muduo::string msg(buf->retrieveAllAsString()); + conn->send(msg); + } + + TcpServer server_; +}; + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(argv[1]); + + muduo::g_logLevel = muduo::Logger::ERROR; + muduo::net::EventLoop loop; + + muduo::net::InetAddress addr(port); + EchoTcpServer server(&loop, addr); + server.start(); + + loop.loop(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/pingpong_client.cpp b/external/libhv/libhv-1.3.2/echo-servers/pingpong_client.cpp new file mode 100644 index 0000000..697e564 --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/pingpong_client.cpp @@ -0,0 +1,143 @@ +#include "hv/hmain.h" // import parse_opt +#include "hv/hloop.h" +#include "hv/hsocket.h" + +#include "hv/EventLoopThreadPool.h" +using namespace hv; + +static const char options[] = "hvH:p:c:d:t:b:"; + +static const char detail_options[] = R"( + -h Print help infomation + -v Show verbose infomation + -H default 127.0.0.1 + -p + -c Number of connections, default: 1000 + -d Duration of test, default: 10s + -t Number of threads, default: 4 + -b Bytes of send buffer, default: 4096 +)"; + +static int connections = 1000; +static int duration = 10; +static int threads = 4; + +static bool verbose = false; +static const char* host = "127.0.0.1"; +static int port = 0; +static int sendbytes = 4096; +static void* sendbuf = NULL; + +static std::atomic connected_num(0); +static std::atomic disconnected_num(0); +static std::atomic total_readcount(0); +static std::atomic total_readbytes(0); + +static void print_help() { + printf("Usage: %s [%s]\n", g_main_ctx.program_name, options); + printf("Options:\n%s\n", detail_options); +} + +static void print_cmd() { + printf("Running %ds test @ %s:%d\n", duration, host, port); + printf("%d threads and %d connections, send %d bytes each time\n", threads, connections, sendbytes); +} + +static void print_result() { + printf("total readcount=%llu readbytes=%llu\n", + (unsigned long long)total_readcount, + (unsigned long long)total_readbytes); + printf("throughput = %llu MB/s\n", (total_readbytes) / ((unsigned long long)duration * 1024 * 1024)); +} + +static void on_close(hio_t* io) { + if (++disconnected_num == connections) { + if (verbose) { + printf("all disconnected\n"); + } + } +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + ++total_readcount; + total_readbytes += readbytes; + hio_write(io, buf, readbytes); +} + +static void on_connect(hio_t* io) { + if (++connected_num == connections) { + if (verbose) { + printf("all connected\n"); + } + } + + hio_write(io, sendbuf, sendbytes); + + hio_setcb_read(io, on_recv); + hio_read_start(io); +} + +static void start_connect(hloop_t* loop) { + hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (io == NULL) { + perror("socket"); + exit(1); + } + tcp_nodelay(hio_fd(io), 1); + hio_setcb_connect(io, on_connect); + hio_setcb_close(io, on_close); + hio_connect(io); +} + +int main(int argc, char** argv) { + // parse cmdline + main_ctx_init(argc, argv); + int ret = parse_opt(argc, argv, options); + if (ret != 0) { + print_help(); + exit(ret); + } + const char* strHost = get_arg("H"); + const char* strPort = get_arg("p"); + const char* strConnections = get_arg("c"); + const char* strDuration = get_arg("d"); + const char* strThreads = get_arg("t"); + const char* strBytes = get_arg("b"); + + if (strHost) host = strHost; + if (strPort) port = atoi(strPort); + if (strConnections) connections = atoi(strConnections); + if (strDuration) duration = atoi(strDuration); + if (strThreads) threads = atoi(strThreads); + if (strBytes) sendbytes = atoi(strBytes); + + if (get_arg("h") || port == 0) { + print_help(); + exit(0); + } + if (get_arg("v")) { + verbose = true; + } + sendbuf = malloc(sendbytes); + + print_cmd(); + + EventLoopThreadPool loop_threads(threads); + loop_threads.start(true); + for (int i = 0; i < connections; ++i) { + EventLoopPtr loop = loop_threads.nextLoop(); + loop->runInLoop(std::bind(start_connect, loop->loop())); + } + + // stop after seconds + loop_threads.loop()->setTimeout(duration * 1000, [&loop_threads](TimerID timerID){ + loop_threads.stop(false); + }); + + // wait loop_threads exit + loop_threads.join(); + + print_result(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/echo-servers/poco_echo.cpp b/external/libhv/libhv-1.3.2/echo-servers/poco_echo.cpp new file mode 100644 index 0000000..715184d --- /dev/null +++ b/external/libhv/libhv-1.3.2/echo-servers/poco_echo.cpp @@ -0,0 +1,225 @@ +// +// EchoServer.cpp +// +// $Id: //poco/1.3/Net/samples/EchoServer/src/EchoServer.cpp#1 $ +// +// This sample demonstrates the SocketReactor and SocketAcceptor classes. +// +// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// Permission is hereby granted, free of charge, to any person or organization +// obtaining a copy of the software and accompanying documentation covered by +// this license (the "Software") to use, reproduce, display, distribute, +// execute, and transmit the Software, and to prepare derivative works of the +// Software, and to permit third-parties to whom the Software is furnished to +// do so, all subject to the following: +// +// The copyright notices in the Software and this entire statement, including +// the above license grant, this restriction and the following disclaimer, +// must be included in all copies of the Software, in whole or in part, and +// all derivative works of the Software, unless such copies or derivative +// works are solely in the form of machine-executable object code generated by +// a source language processor. +// +// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT +// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. +// + + +#include "Poco/Net/SocketReactor.h" +#include "Poco/Net/SocketAcceptor.h" +#include "Poco/Net/SocketNotification.h" +#include "Poco/Net/StreamSocket.h" +#include "Poco/Net/ServerSocket.h" +#include "Poco/NObserver.h" +#include "Poco/Exception.h" +#include "Poco/Thread.h" +#include "Poco/Util/ServerApplication.h" +#include "Poco/Util/Option.h" +#include "Poco/Util/OptionSet.h" +#include "Poco/Util/HelpFormatter.h" +#include + + +using Poco::Net::SocketReactor; +using Poco::Net::SocketAcceptor; +using Poco::Net::ReadableNotification; +using Poco::Net::ShutdownNotification; +using Poco::Net::ServerSocket; +using Poco::Net::StreamSocket; +using Poco::NObserver; +using Poco::AutoPtr; +using Poco::Thread; +using Poco::Util::ServerApplication; +using Poco::Util::Application; +using Poco::Util::Option; +using Poco::Util::OptionSet; +using Poco::Util::HelpFormatter; + + +class EchoServiceHandler +{ +public: + EchoServiceHandler(StreamSocket& socket, SocketReactor& reactor): + _socket(socket), + _reactor(reactor), + _pBuffer(new char[BUFFER_SIZE]) + { + // Application& app = Application::instance(); + // app.logger().information("Connection from " + socket.peerAddress().toString()); + + _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); + _reactor.addEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); + } + + ~EchoServiceHandler() + { + // Application& app = Application::instance(); + // app.logger().information("Disconnecting " + _socket.peerAddress().toString()); + + _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onReadable)); + _reactor.removeEventHandler(_socket, NObserver(*this, &EchoServiceHandler::onShutdown)); + delete [] _pBuffer; + } + + void onReadable(const AutoPtr& pNf) + { + int n = _socket.receiveBytes(_pBuffer, BUFFER_SIZE); + if (n > 0) + _socket.sendBytes(_pBuffer, n); + else + delete this; + } + + void onShutdown(const AutoPtr& pNf) + { + delete this; + } + +private: + enum + { + BUFFER_SIZE = 1024 + }; + + StreamSocket _socket; + SocketReactor& _reactor; + char* _pBuffer; +}; + + +class EchoServer: public Poco::Util::ServerApplication + /// The main application class. + /// + /// This class handles command-line arguments and + /// configuration files. + /// Start the EchoServer executable with the help + /// option (/help on Windows, --help on Unix) for + /// the available command line options. + /// + /// To use the sample configuration file (EchoServer.properties), + /// copy the file to the directory where the EchoServer executable + /// resides. If you start the debug version of the EchoServer + /// (EchoServerd[.exe]), you must also create a copy of the configuration + /// file named EchoServerd.properties. In the configuration file, you + /// can specify the port on which the server is listening (default + /// 9977) and the format of the date/time string sent back to the client. + /// + /// To test the EchoServer you can use any telnet client (telnet localhost 9977). +{ +public: + EchoServer(): _helpRequested(false) + { + } + + ~EchoServer() + { + } + +protected: + void initialize(Application& self) + { + loadConfiguration(); // load default configuration files, if present + ServerApplication::initialize(self); + } + + void uninitialize() + { + ServerApplication::uninitialize(); + } + + void defineOptions(OptionSet& options) + { + ServerApplication::defineOptions(options); + + options.addOption( + Option("help", "h", "display help information on command line arguments") + .required(false) + .repeatable(false)); + } + + void handleOption(const std::string& name, const std::string& value) + { + ServerApplication::handleOption(name, value); + + if (name == "help") + _helpRequested = true; + } + + void displayHelp() + { + HelpFormatter helpFormatter(options()); + helpFormatter.setCommand(commandName()); + helpFormatter.setUsage("OPTIONS"); + helpFormatter.setHeader("An echo server implemented using the Reactor and Acceptor patterns."); + helpFormatter.format(std::cout); + } + + int main(const std::vector& args) + { + if (_helpRequested) + { + displayHelp(); + } + else + { + if (args.size() < 1) { + printf("Usage: cmd port\n"); + return -10; + } + int port = atoi(args[0].c_str()); + // set-up a server socket + ServerSocket svs(port); + // set-up a SocketReactor... + SocketReactor reactor; + // ... and a SocketAcceptor + SocketAcceptor acceptor(svs, reactor); + // run the reactor in its own thread so that we can wait for + // a termination request + Thread thread; + thread.start(reactor); + // wait for CTRL-C or kill + waitForTerminationRequest(); + // Stop the SocketReactor + reactor.stop(); + thread.join(); + } + return Application::EXIT_OK; + } + +private: + bool _helpRequested; +}; + + +int main(int argc, char** argv) +{ + EchoServer app; + return app.run(argc, argv); +} diff --git a/external/libhv/libhv-1.3.2/etc/hmain_test.conf b/external/libhv/libhv-1.3.2/etc/hmain_test.conf new file mode 100644 index 0000000..33c7196 --- /dev/null +++ b/external/libhv/libhv-1.3.2/etc/hmain_test.conf @@ -0,0 +1,13 @@ +# [root] + +# logfile = logs/test.log +# loglevel = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] +loglevel = DEBUG +log_remain_days = 3 +log_filesize = 16M + +# worker_processes = auto # auto = ncpu +worker_processes = auto +worker_threads = 2 + +port = 8086 diff --git a/external/libhv/libhv-1.3.2/etc/httpd.conf b/external/libhv/libhv-1.3.2/etc/httpd.conf new file mode 100644 index 0000000..74e8260 --- /dev/null +++ b/external/libhv/libhv-1.3.2/etc/httpd.conf @@ -0,0 +1,54 @@ +# [root] + +# logfile = logs/httpd.log +# loglevel = [VERBOSE,DEBUG,INFO,WARN,ERROR,FATAL,SILENT] +loglevel = INFO +log_remain_days = 3 +log_filesize = 64M + +# multi-processes mode +# auto = ncpu +worker_processes = auto +worker_threads = 1 + +# multi-threads mode +# worker_processes = 1 +# worker_threads = auto + +# Disable multi-processes mode for debugging +# worker_processes = 0 + +# max_connections = workers * worker_connections +worker_connections = 1024 + +# http server +http_port = 8080 +https_port = 8443 +#base_url = /api/v1 +document_root = html +home_page = index.html +#error_page = error.html +index_of = /downloads/ +keepalive_timeout = 75000 # ms +limit_rate = 500 # KB/s +access_log = off +cors = true + +# SSL/TLS +ssl_certificate = cert/server.crt +ssl_privatekey = cert/server.key +ssl_ca_certificate = cert/cacert.pem + +# proxy +[proxy] +proxy_connect_timeout = 10000 # ms +proxy_read_timeout = 60000 # ms +proxy_write_timeout = 60000 # ms +# forward proxy +forward_proxy = true +trust_proxies = *httpbin.org;*postman-echo.com;*apifox.com +#no_proxies = * +# reverse proxy +/httpbin/ => http://httpbin.org/ +/postman/ => http://postman-echo.com/ +/apifox/ => https://echo.apifox.com/ diff --git a/external/libhv/libhv-1.3.2/etc/nginx.conf b/external/libhv/libhv-1.3.2/etc/nginx.conf new file mode 100644 index 0000000..11670c5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/etc/nginx.conf @@ -0,0 +1,37 @@ +# cd libhv +# sudo nginx -p . -c etc/nginx.conf +# bin/httpd -c etc/httpd.conf -s restart -d +# bin/curl -v http://127.0.0.1/api/v1/get + +worker_processes auto; + +pid logs/nginx.pid; +error_log logs/error.log; + +events { + worker_connections 1024; +} + +http { + access_log logs/access.log; + + server { + listen 80; + + # static files service + location / { + root html; + index index.html; + } + + # autoindex service + location /downloads/ { + autoindex on; + } + + # api service: nginx => libhv + location /api/v1/ { + proxy_pass http://127.0.0.1:8080/; + } + } +} diff --git a/external/libhv/libhv-1.3.2/event/README.md b/external/libhv/libhv-1.3.2/event/README.md new file mode 100644 index 0000000..d928342 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/README.md @@ -0,0 +1,20 @@ +## 目录结构 + +``` +. +├── hloop.h 事件循环模块对外头文件 +├── hevent.h 事件结构体定义 +├── nlog.h 网络日志 +├── unpack.h 拆包 +├── rudp.h 可靠UDP +├── iowatcher.h IO多路复用统一抽象接口 +├── select.c EVENT_SELECT实现 +├── poll.c EVENT_POLL实现 +├── epoll.c EVENT_EPOLL实现 (for OS_LINUX) +├── iocp.c EVENT_IOCP实现 (for OS_WIN) +├── kqueue.c EVENT_KQUEUE实现(for OS_BSD/OS_MAC) +├── evport.c EVENT_PORT实现 (for OS_SOLARIS) +├── nio.c 非阻塞IO +└── overlapio.c 重叠IO + +``` diff --git a/external/libhv/libhv-1.3.2/event/epoll.c b/external/libhv/libhv-1.3.2/event/epoll.c new file mode 100644 index 0000000..dece40a --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/epoll.c @@ -0,0 +1,143 @@ +#include "iowatcher.h" + +#ifdef EVENT_EPOLL +#include "hplatform.h" +#include "hdef.h" +#include "hevent.h" + +#ifdef OS_WIN +#include "wepoll/wepoll.h" +#else +#include +#define epoll_close(epfd) close(epfd) +#endif + +#include "array.h" +#define EVENTS_INIT_SIZE 64 +ARRAY_DECL(struct epoll_event, events); + +typedef struct epoll_ctx_s { + int epfd; + struct events events; +} epoll_ctx_t; + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + epoll_ctx_t* epoll_ctx; + HV_ALLOC_SIZEOF(epoll_ctx); + epoll_ctx->epfd = epoll_create(EVENTS_INIT_SIZE); + events_init(&epoll_ctx->events, EVENTS_INIT_SIZE); + loop->iowatcher = epoll_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + if (loop->iowatcher == NULL) return 0; + epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; + epoll_close(epoll_ctx->epfd); + events_cleanup(&epoll_ctx->events); + HV_FREE(loop->iowatcher); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; + hio_t* io = loop->ios.ptr[fd]; + + struct epoll_event ee; + memset(&ee, 0, sizeof(ee)); + ee.data.fd = fd; + // pre events + if (io->events & HV_READ) { + ee.events |= EPOLLIN; + } + if (io->events & HV_WRITE) { + ee.events |= EPOLLOUT; + } + // now events + if (events & HV_READ) { + ee.events |= EPOLLIN; + } + if (events & HV_WRITE) { + ee.events |= EPOLLOUT; + } + int op = io->events == 0 ? EPOLL_CTL_ADD : EPOLL_CTL_MOD; + epoll_ctl(epoll_ctx->epfd, op, fd, &ee); + if (op == EPOLL_CTL_ADD) { + if (epoll_ctx->events.size == epoll_ctx->events.maxsize) { + events_double_resize(&epoll_ctx->events); + } + epoll_ctx->events.size++; + } + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; + if (epoll_ctx == NULL) return 0; + hio_t* io = loop->ios.ptr[fd]; + + struct epoll_event ee; + memset(&ee, 0, sizeof(ee)); + ee.data.fd = fd; + // pre events + if (io->events & HV_READ) { + ee.events |= EPOLLIN; + } + if (io->events & HV_WRITE) { + ee.events |= EPOLLOUT; + } + // now events + if (events & HV_READ) { + ee.events &= ~EPOLLIN; + } + if (events & HV_WRITE) { + ee.events &= ~EPOLLOUT; + } + int op = ee.events == 0 ? EPOLL_CTL_DEL : EPOLL_CTL_MOD; + epoll_ctl(epoll_ctx->epfd, op, fd, &ee); + if (op == EPOLL_CTL_DEL) { + epoll_ctx->events.size--; + } + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + epoll_ctx_t* epoll_ctx = (epoll_ctx_t*)loop->iowatcher; + if (epoll_ctx == NULL) return 0; + if (epoll_ctx->events.size == 0) return 0; + int nepoll = epoll_wait(epoll_ctx->epfd, epoll_ctx->events.ptr, epoll_ctx->events.size, timeout); + if (nepoll < 0) { + if (errno == EINTR) { + return 0; + } + perror("epoll"); + return nepoll; + } + if (nepoll == 0) return 0; + int nevents = 0; + for (int i = 0; i < epoll_ctx->events.size; ++i) { + struct epoll_event* ee = epoll_ctx->events.ptr + i; + int fd = ee->data.fd; + uint32_t revents = ee->events; + if (revents) { + ++nevents; + hio_t* io = loop->ios.ptr[fd]; + if (io) { + if (revents & (EPOLLIN | EPOLLHUP | EPOLLERR)) { + io->revents |= HV_READ; + } + if (revents & (EPOLLOUT | EPOLLHUP | EPOLLERR)) { + io->revents |= HV_WRITE; + } + EVENT_PENDING(io); + } + } + if (nevents == nepoll) break; + } + return nevents; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/evport.c b/external/libhv/libhv-1.3.2/event/evport.c new file mode 100644 index 0000000..8976dec --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/evport.c @@ -0,0 +1,137 @@ +#include "iowatcher.h" + +#ifdef EVENT_PORT + +#include "hplatform.h" +#include "hdef.h" +#include "hevent.h" + +#include + +#define EVENTS_INIT_SIZE 64 + +typedef struct evport_ctx_s { + int port; + int capacity; + int nevents; + port_event_t* events; +} evport_ctx_t; + +static void evport_ctx_resize(evport_ctx_t* evport_ctx, int size) { + int bytes = sizeof(port_event_t) * size; + int oldbytes = sizeof(port_event_t) * evport_ctx->capacity; + evport_ctx->events = (port_event_t*)hv_realloc(evport_ctx->events, bytes, oldbytes); + evport_ctx->capacity = size; +} + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + evport_ctx_t* evport_ctx; + HV_ALLOC_SIZEOF(evport_ctx); + evport_ctx->port = port_create(); + evport_ctx->capacity = EVENTS_INIT_SIZE; + evport_ctx->nevents = 0; + int bytes = sizeof(port_event_t) * evport_ctx->capacity; + HV_ALLOC(evport_ctx->events, bytes); + loop->iowatcher = evport_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + if (loop->iowatcher == NULL) return 0; + evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; + close(evport_ctx->port); + HV_FREE(evport_ctx->events); + HV_FREE(loop->iowatcher); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; + hio_t* io = loop->ios.ptr[fd]; + + int evport_events = 0; + if (io->events & HV_READ) { + evport_events |= POLLIN; + } + if (io->events & HV_WRITE) { + evport_events |= POLLOUT; + } + if (events & HV_READ) { + evport_events |= POLLIN; + } + if (events & HV_WRITE) { + evport_events |= POLLOUT; + } + port_associate(evport_ctx->port, PORT_SOURCE_FD, fd, evport_events, NULL); + if (io->events == 0) { + if (evport_ctx->nevents == evport_ctx->capacity) { + evport_ctx_resize(evport_ctx, evport_ctx->capacity * 2); + } + ++evport_ctx->nevents; + } + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; + if (evport_ctx == NULL) return 0; + hio_t* io = loop->ios.ptr[fd]; + + int evport_events = 0; + if (io->events & HV_READ) { + evport_events |= POLLIN; + } + if (io->events & HV_WRITE) { + evport_events |= POLLOUT; + } + if (events & HV_READ) { + evport_events &= ~POLLIN; + } + if (events & HV_WRITE) { + evport_events &= ~POLLOUT; + } + if (evport_events == 0) { + port_dissociate(evport_ctx->port, PORT_SOURCE_FD, fd); + --evport_ctx->nevents; + } else { + port_associate(evport_ctx->port, PORT_SOURCE_FD, fd, evport_events, NULL); + } + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + evport_ctx_t* evport_ctx = (evport_ctx_t*)loop->iowatcher; + if (evport_ctx == NULL) return 0; + struct timespec ts, *tp; + if (timeout == INFINITE) { + tp = NULL; + } else { + ts.tv_sec = timeout / 1000; + ts.tv_nsec = (timeout % 1000) * 1000000; + tp = &ts; + } + unsigned nevents = 1; + port_getn(evport_ctx->port, evport_ctx->events, evport_ctx->capacity, &nevents, tp); + for (int i = 0; i < nevents; ++i) { + int fd = evport_ctx->events[i].portev_object; + int revents = evport_ctx->events[i].portev_events; + hio_t* io = loop->ios.ptr[fd]; + if (io) { + if (revents & POLLIN) { + io->revents |= HV_READ; + } + if (revents & POLLOUT) { + io->revents |= HV_WRITE; + } + EVENT_PENDING(io); + } + // Upon retrieval, the event object is no longer associated with the port. + iowatcher_add_event(loop, fd, io->events); + } + return nevents; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/hevent.c b/external/libhv/libhv-1.3.2/event/hevent.c new file mode 100644 index 0000000..a9a75b9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/hevent.c @@ -0,0 +1,938 @@ +#include "hevent.h" +#include "hsocket.h" +#include "hatomic.h" +#include "hlog.h" +#include "herr.h" + +#include "unpack.h" + +uint64_t hloop_next_event_id() { + static hatomic_t s_id = HATOMIC_VAR_INIT(0); + return ++s_id; +} + +uint32_t hio_next_id() { + static hatomic_t s_id = HATOMIC_VAR_INIT(0); + return ++s_id; +} + +static void fill_io_type(hio_t* io) { + int type = 0; + socklen_t optlen = sizeof(int); + int ret = getsockopt(io->fd, SOL_SOCKET, SO_TYPE, (char*)&type, &optlen); + printd("getsockopt SO_TYPE fd=%d ret=%d type=%d errno=%d\n", io->fd, ret, type, socket_errno()); + if (ret == 0) { + switch (type) { + case SOCK_STREAM: io->io_type = HIO_TYPE_TCP; break; + case SOCK_DGRAM: io->io_type = HIO_TYPE_UDP; break; + case SOCK_RAW: io->io_type = HIO_TYPE_IP; break; + default: io->io_type = HIO_TYPE_SOCKET; break; + } + } + else if (socket_errno() == ENOTSOCK) { + switch (io->fd) { + case 0: io->io_type = HIO_TYPE_STDIN; break; + case 1: io->io_type = HIO_TYPE_STDOUT; break; + case 2: io->io_type = HIO_TYPE_STDERR; break; + default: io->io_type = HIO_TYPE_FILE; break; + } + } + else { + io->io_type = HIO_TYPE_TCP; + } +} + +static void hio_socket_init(hio_t* io) { + if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { + // NOTE: sendto multiple peeraddr cannot use io->write_queue + blocking(io->fd); + } else { + nonblocking(io->fd); + } + // fill io->localaddr io->peeraddr + if (io->localaddr == NULL) { + HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); + } + if (io->peeraddr == NULL) { + HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); + } + socklen_t addrlen = sizeof(sockaddr_u); + int ret = getsockname(io->fd, io->localaddr, &addrlen); + printd("getsockname fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno()); + // NOTE: udp peeraddr set by recvfrom/sendto + if (io->io_type & HIO_TYPE_SOCK_STREAM) { + addrlen = sizeof(sockaddr_u); + ret = getpeername(io->fd, io->peeraddr, &addrlen); + printd("getpeername fd=%d ret=%d errno=%d\n", io->fd, ret, socket_errno()); + } +} + +void hio_init(hio_t* io) { + // alloc localaddr,peeraddr when hio_socket_init + /* + if (io->localaddr == NULL) { + HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); + } + if (io->peeraddr == NULL) { + HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); + } + */ + + // write_queue init when hwrite try_write failed + // write_queue_init(&io->write_queue, 4); + + hrecursive_mutex_init(&io->write_mutex); +} + +void hio_ready(hio_t* io) { + if (io->ready) return; + // flags + io->ready = 1; + io->connected = 0; + io->closed = 0; + io->accept = io->connect = io->connectex = 0; + io->recv = io->send = 0; + io->recvfrom = io->sendto = 0; + io->close = 0; + // public: + io->id = hio_next_id(); + io->io_type = HIO_TYPE_UNKNOWN; + io->error = 0; + io->events = io->revents = 0; + io->last_read_hrtime = io->last_write_hrtime = io->loop->cur_hrtime; + // readbuf + io->alloced_readbuf = 0; + hio_use_loop_readbuf(io); + io->readbuf.head = io->readbuf.tail = 0; + io->read_flags = 0; + io->read_until_length = 0; + io->max_read_bufsize = MAX_READ_BUFSIZE; + io->small_readbytes_cnt = 0; + // write_queue + io->write_bufsize = 0; + io->max_write_bufsize = MAX_WRITE_BUFSIZE; + // callbacks + io->read_cb = NULL; + io->write_cb = NULL; + io->close_cb = NULL; + io->accept_cb = NULL; + io->connect_cb = NULL; + // timers + io->connect_timeout = 0; + io->connect_timer = NULL; + io->close_timeout = 0; + io->close_timer = NULL; + io->read_timeout = 0; + io->read_timer = NULL; + io->write_timeout = 0; + io->write_timer = NULL; + io->keepalive_timeout = 0; + io->keepalive_timer = NULL; + io->heartbeat_interval = 0; + io->heartbeat_fn = NULL; + io->heartbeat_timer = NULL; + // upstream + io->upstream_io = NULL; + // unpack + io->unpack_setting = NULL; + // ssl + io->ssl = NULL; + io->ssl_ctx = NULL; + io->alloced_ssl_ctx = 0; + io->hostname = NULL; + // context + io->ctx = NULL; + // private: +#if defined(EVENT_POLL) || defined(EVENT_KQUEUE) + io->event_index[0] = io->event_index[1] = -1; +#endif +#ifdef EVENT_IOCP + io->hovlp = NULL; +#endif + + // io_type + fill_io_type(io); + if (io->io_type & HIO_TYPE_SOCKET) { + hio_socket_init(io); + } + +#if WITH_RUDP + if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { + rudp_init(&io->rudp); + } +#endif +} + +void hio_done(hio_t* io) { + if (!io->ready) return; + io->ready = 0; + + hio_del(io, HV_RDWR); + + // readbuf + hio_free_readbuf(io); + + // write_queue + offset_buf_t* pbuf = NULL; + hrecursive_mutex_lock(&io->write_mutex); + while (!write_queue_empty(&io->write_queue)) { + pbuf = write_queue_front(&io->write_queue); + HV_FREE(pbuf->base); + write_queue_pop_front(&io->write_queue); + } + write_queue_cleanup(&io->write_queue); + hrecursive_mutex_unlock(&io->write_mutex); + +#if WITH_RUDP + if ((io->io_type & HIO_TYPE_SOCK_DGRAM) || (io->io_type & HIO_TYPE_SOCK_RAW)) { + rudp_cleanup(&io->rudp); + } +#endif +} + +void hio_free(hio_t* io) { + if (io == NULL) return; + hio_close(io); + hrecursive_mutex_destroy(&io->write_mutex); + HV_FREE(io->localaddr); + HV_FREE(io->peeraddr); + HV_FREE(io); +} + +bool hio_is_opened(hio_t* io) { + if (io == NULL) return false; + return io->ready == 1 && io->closed == 0; +} + +bool hio_is_connected(hio_t* io) { + if (io == NULL) return false; + return io->ready == 1 && io->connected == 1 && io->closed == 0; +} + +bool hio_is_closed(hio_t* io) { + if (io == NULL) return true; + return io->ready == 0 && io->closed == 1; +} + +uint32_t hio_id (hio_t* io) { + return io->id; +} + +int hio_fd(hio_t* io) { + return io->fd; +} + +hio_type_e hio_type(hio_t* io) { + return io->io_type; +} + +int hio_error(hio_t* io) { + return io->error; +} + +int hio_events(hio_t* io) { + return io->events; +} + +int hio_revents(hio_t* io) { + return io->revents; +} + +struct sockaddr* hio_localaddr(hio_t* io) { + return io->localaddr; +} + +struct sockaddr* hio_peeraddr(hio_t* io) { + return io->peeraddr; +} + +void hio_set_context(hio_t* io, void* ctx) { + io->ctx = ctx; +} + +void* hio_context(hio_t* io) { + return io->ctx; +} + +haccept_cb hio_getcb_accept(hio_t* io) { + return io->accept_cb; +} + +hconnect_cb hio_getcb_connect(hio_t* io) { + return io->connect_cb; +} + +hread_cb hio_getcb_read(hio_t* io) { + return io->read_cb; +} + +hwrite_cb hio_getcb_write(hio_t* io) { + return io->write_cb; +} + +hclose_cb hio_getcb_close(hio_t* io) { + return io->close_cb; +} + +void hio_setcb_accept(hio_t* io, haccept_cb accept_cb) { + io->accept_cb = accept_cb; +} + +void hio_setcb_connect(hio_t* io, hconnect_cb connect_cb) { + io->connect_cb = connect_cb; +} + +void hio_setcb_read(hio_t* io, hread_cb read_cb) { + io->read_cb = read_cb; +} + +void hio_setcb_write(hio_t* io, hwrite_cb write_cb) { + io->write_cb = write_cb; +} + +void hio_setcb_close(hio_t* io, hclose_cb close_cb) { + io->close_cb = close_cb; +} + +void hio_accept_cb(hio_t* io) { + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("accept connfd=%d [%s] <= [%s]\n", io->fd, + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + */ + if (io->accept_cb) { + // printd("accept_cb------\n"); + io->accept_cb(io); + // printd("accept_cb======\n"); + } +} + +void hio_connect_cb(hio_t* io) { + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("connect connfd=%d [%s] => [%s]\n", io->fd, + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + */ + io->connected = 1; + if (io->connect_cb) { + // printd("connect_cb------\n"); + io->connect_cb(io); + // printd("connect_cb======\n"); + } +} + +void hio_handle_read(hio_t* io, void* buf, int readbytes) { +#if WITH_KCP + if (io->io_type == HIO_TYPE_KCP) { + hio_read_kcp(io, buf, readbytes); + io->readbuf.head = io->readbuf.tail = 0; + return; + } +#endif + + if (io->unpack_setting) { + // hio_set_unpack + hio_unpack(io, buf, readbytes); + } else { + const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; + const unsigned char* ep = (const unsigned char*)buf + readbytes; + if (io->read_flags & HIO_READ_UNTIL_LENGTH) { + // hio_read_until_length + if (ep - sp >= io->read_until_length) { + io->readbuf.head += io->read_until_length; + if (io->readbuf.head == io->readbuf.tail) { + io->readbuf.head = io->readbuf.tail = 0; + } + io->read_flags &= ~HIO_READ_UNTIL_LENGTH; + hio_read_cb(io, (void*)sp, io->read_until_length); + } + } else if (io->read_flags & HIO_READ_UNTIL_DELIM) { + // hio_read_until_delim + const unsigned char* p = (const unsigned char*)buf; + for (int i = 0; i < readbytes; ++i, ++p) { + if (*p == io->read_until_delim) { + int len = p - sp + 1; + io->readbuf.head += len; + if (io->readbuf.head == io->readbuf.tail) { + io->readbuf.head = io->readbuf.tail = 0; + } + io->read_flags &= ~HIO_READ_UNTIL_DELIM; + hio_read_cb(io, (void*)sp, len); + return; + } + } + } else { + // hio_read + io->readbuf.head = io->readbuf.tail = 0; + hio_read_cb(io, (void*)sp, ep - sp); + } + } + + if (io->readbuf.head == io->readbuf.tail) { + io->readbuf.head = io->readbuf.tail = 0; + } + // readbuf autosize + if (io->readbuf.tail == io->readbuf.len) { + if (io->readbuf.head == 0) { + // scale up * 2 + hio_alloc_readbuf(io, io->readbuf.len * 2); + } else { + hio_memmove_readbuf(io); + } + } else { + size_t small_size = io->readbuf.len / 2; + if (io->readbuf.tail < small_size && + io->small_readbytes_cnt >= 3) { + // scale down / 2 + hio_alloc_readbuf(io, small_size); + } + } +} + +void hio_read_cb(hio_t* io, void* buf, int len) { + if (io->read_flags & HIO_READ_ONCE) { + io->read_flags &= ~HIO_READ_ONCE; + hio_read_stop(io); + } + + if (io->read_cb) { + // printd("read_cb------\n"); + io->read_cb(io, buf, len); + // printd("read_cb======\n"); + } + + // for readbuf autosize + if (hio_is_alloced_readbuf(io) && io->readbuf.len > READ_BUFSIZE_HIGH_WATER) { + size_t small_size = io->readbuf.len / 2; + if (len < small_size) { + ++io->small_readbytes_cnt; + } else { + io->small_readbytes_cnt = 0; + } + } +} + +void hio_write_cb(hio_t* io, const void* buf, int len) { + if (io->write_cb) { + // printd("write_cb------\n"); + io->write_cb(io, buf, len); + // printd("write_cb======\n"); + } +} + +void hio_close_cb(hio_t* io) { + io->connected = 0; + io->closed = 1; + if (io->close_cb) { + // printd("close_cb------\n"); + io->close_cb(io); + // printd("close_cb======\n"); + } +} + +void hio_set_type(hio_t* io, hio_type_e type) { + io->io_type = type; +} + +void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen) { + if (io->localaddr == NULL) { + HV_ALLOC(io->localaddr, sizeof(sockaddr_u)); + } + memcpy(io->localaddr, addr, addrlen); +} + +void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen) { + if (io->peeraddr == NULL) { + HV_ALLOC(io->peeraddr, sizeof(sockaddr_u)); + } + memcpy(io->peeraddr, addr, addrlen); +} + +int hio_enable_ssl(hio_t* io) { + io->io_type = HIO_TYPE_SSL; + return 0; +} + +bool hio_is_ssl(hio_t* io) { + return io->io_type == HIO_TYPE_SSL; +} + +hssl_t hio_get_ssl(hio_t* io) { + return io->ssl; +} + +hssl_ctx_t hio_get_ssl_ctx(hio_t* io) { + return io->ssl_ctx; +} + +int hio_set_ssl(hio_t* io, hssl_t ssl) { + io->io_type = HIO_TYPE_SSL; + io->ssl = ssl; + return 0; +} + +int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx) { + io->io_type = HIO_TYPE_SSL; + io->ssl_ctx = ssl_ctx; + return 0; +} + +int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt) { + hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); + if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; + io->alloced_ssl_ctx = 1; + return hio_set_ssl_ctx(io, ssl_ctx); +} + +int hio_set_hostname(hio_t* io, const char* hostname) { + SAFE_FREE(io->hostname); + io->hostname = strdup(hostname); + return 0; +} + +const char* hio_get_hostname(hio_t* io) { + return io->hostname; +} + +void hio_del_connect_timer(hio_t* io) { + if (io->connect_timer) { + htimer_del(io->connect_timer); + io->connect_timer = NULL; + io->connect_timeout = 0; + } +} + +void hio_del_close_timer(hio_t* io) { + if (io->close_timer) { + htimer_del(io->close_timer); + io->close_timer = NULL; + io->close_timeout = 0; + } +} + +void hio_del_read_timer(hio_t* io) { + if (io->read_timer) { + htimer_del(io->read_timer); + io->read_timer = NULL; + io->read_timeout = 0; + } +} + +void hio_del_write_timer(hio_t* io) { + if (io->write_timer) { + htimer_del(io->write_timer); + io->write_timer = NULL; + io->write_timeout = 0; + } +} + +void hio_del_keepalive_timer(hio_t* io) { + if (io->keepalive_timer) { + htimer_del(io->keepalive_timer); + io->keepalive_timer = NULL; + io->keepalive_timeout = 0; + } +} + +void hio_del_heartbeat_timer(hio_t* io) { + if (io->heartbeat_timer) { + htimer_del(io->heartbeat_timer); + io->heartbeat_timer = NULL; + io->heartbeat_interval = 0; + io->heartbeat_fn = NULL; + } +} + +void hio_set_connect_timeout(hio_t* io, int timeout_ms) { + io->connect_timeout = timeout_ms; +} + +void hio_set_close_timeout(hio_t* io, int timeout_ms) { + io->close_timeout = timeout_ms; +} + +static void __read_timeout_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + uint64_t inactive_ms = (io->loop->cur_hrtime - io->last_read_hrtime) / 1000; + if (inactive_ms + 100 < io->read_timeout) { + htimer_reset(io->read_timer, io->read_timeout - inactive_ms); + } else { + if (io->io_type & HIO_TYPE_SOCKET) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + hlogw("read timeout [%s] <=> [%s]", + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + } + io->error = ETIMEDOUT; + hio_close(io); + } +} + +void hio_set_read_timeout(hio_t* io, int timeout_ms) { + if (timeout_ms <= 0) { + // del + hio_del_read_timer(io); + return; + } + + if (io->read_timer) { + // reset + htimer_reset(io->read_timer, timeout_ms); + } else { + // add + io->read_timer = htimer_add(io->loop, __read_timeout_cb, timeout_ms, 1); + io->read_timer->privdata = io; + } + io->read_timeout = timeout_ms; +} + +static void __write_timeout_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + uint64_t inactive_ms = (io->loop->cur_hrtime - io->last_write_hrtime) / 1000; + if (inactive_ms + 100 < io->write_timeout) { + htimer_reset(io->write_timer, io->write_timeout - inactive_ms); + } else { + if (io->io_type & HIO_TYPE_SOCKET) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + hlogw("write timeout [%s] <=> [%s]", + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + } + io->error = ETIMEDOUT; + hio_close(io); + } +} + +void hio_set_write_timeout(hio_t* io, int timeout_ms) { + if (timeout_ms <= 0) { + // del + hio_del_write_timer(io); + return; + } + + if (io->write_timer) { + // reset + htimer_reset(io->write_timer, timeout_ms); + } else { + // add + io->write_timer = htimer_add(io->loop, __write_timeout_cb, timeout_ms, 1); + io->write_timer->privdata = io; + } + io->write_timeout = timeout_ms; +} + +static void __keepalive_timeout_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + uint64_t last_rw_hrtime = MAX(io->last_read_hrtime, io->last_write_hrtime); + uint64_t inactive_ms = (io->loop->cur_hrtime - last_rw_hrtime) / 1000; + if (inactive_ms + 100 < io->keepalive_timeout) { + htimer_reset(io->keepalive_timer, io->keepalive_timeout - inactive_ms); + } else { + if (io->io_type & HIO_TYPE_SOCKET) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + hlogw("keepalive timeout [%s] <=> [%s]", + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + } + io->error = ETIMEDOUT; + hio_close(io); + } +} + +void hio_set_keepalive_timeout(hio_t* io, int timeout_ms) { + if (timeout_ms <= 0) { + // del + hio_del_keepalive_timer(io); + return; + } + + if (io->keepalive_timer) { + // reset + htimer_reset(io->keepalive_timer, timeout_ms); + } else { + // add + io->keepalive_timer = htimer_add(io->loop, __keepalive_timeout_cb, timeout_ms, 1); + io->keepalive_timer->privdata = io; + } + io->keepalive_timeout = timeout_ms; +} + +static void __heartbeat_timer_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + if (io && io->heartbeat_fn) { + io->heartbeat_fn(io); + } +} + +void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn) { + if (interval_ms <= 0) { + // del + hio_del_heartbeat_timer(io); + return; + } + + if (io->heartbeat_timer) { + // reset + htimer_reset(io->heartbeat_timer, interval_ms); + } else { + // add + io->heartbeat_timer = htimer_add(io->loop, __heartbeat_timer_cb, interval_ms, INFINITE); + io->heartbeat_timer->privdata = io; + } + io->heartbeat_interval = interval_ms; + io->heartbeat_fn = fn; +} + +//-----------------iobuf--------------------------------------------- +void hio_alloc_readbuf(hio_t* io, int len) { + if (len > io->max_read_bufsize) { + hloge("read bufsize > %u, close it!", io->max_read_bufsize); + io->error = ERR_OVER_LIMIT; + hio_close_async(io); + return; + } + if (hio_is_alloced_readbuf(io)) { + io->readbuf.base = (char*)hv_realloc(io->readbuf.base, len, io->readbuf.len); + } else { + HV_ALLOC(io->readbuf.base, len); + } + io->readbuf.len = len; + io->alloced_readbuf = 1; + io->small_readbytes_cnt = 0; +} + +void hio_free_readbuf(hio_t* io) { + if (hio_is_alloced_readbuf(io)) { + HV_FREE(io->readbuf.base); + io->alloced_readbuf = 0; + // reset to loop->readbuf + io->readbuf.base = io->loop->readbuf.base; + io->readbuf.len = io->loop->readbuf.len; + } +} + +void hio_memmove_readbuf(hio_t* io) { + fifo_buf_t* buf = &io->readbuf; + if (buf->tail == buf->head) { + buf->head = buf->tail = 0; + return; + } + if (buf->tail > buf->head) { + size_t size = buf->tail - buf->head; + // [head, tail] => [0, tail - head] + memmove(buf->base, buf->base + buf->head, size); + buf->head = 0; + buf->tail = size; + } +} + +void hio_set_readbuf(hio_t* io, void* buf, size_t len) { + assert(io && buf && len != 0); + hio_free_readbuf(io); + io->readbuf.base = (char*)buf; + io->readbuf.len = len; + io->readbuf.head = io->readbuf.tail = 0; + io->alloced_readbuf = 0; +} + +hio_readbuf_t* hio_get_readbuf(hio_t* io) { + return &io->readbuf; +} + +void hio_set_max_read_bufsize (hio_t* io, uint32_t size) { + io->max_read_bufsize = size; +} + +void hio_set_max_write_bufsize(hio_t* io, uint32_t size) { + io->max_write_bufsize = size; +} + +size_t hio_write_bufsize(hio_t* io) { + return io->write_bufsize; +} + +int hio_read_once (hio_t* io) { + io->read_flags |= HIO_READ_ONCE; + return hio_read_start(io); +} + +int hio_read_until_length(hio_t* io, unsigned int len) { + if (len == 0) return 0; + if (io->readbuf.tail - io->readbuf.head >= len) { + void* buf = io->readbuf.base + io->readbuf.head; + io->readbuf.head += len; + if (io->readbuf.head == io->readbuf.tail) { + io->readbuf.head = io->readbuf.tail = 0; + } + hio_read_cb(io, buf, len); + return len; + } + io->read_flags = HIO_READ_UNTIL_LENGTH; + io->read_until_length = len; + if (io->readbuf.head > 1024 || io->readbuf.tail - io->readbuf.head < 1024) { + hio_memmove_readbuf(io); + } + // NOTE: prepare readbuf + int need_len = io->readbuf.head + len; + if (hio_is_loop_readbuf(io) || + io->readbuf.len < need_len) { + hio_alloc_readbuf(io, need_len); + } + return hio_read_once(io); +} + +int hio_read_until_delim(hio_t* io, unsigned char delim) { + if (io->readbuf.tail - io->readbuf.head > 0) { + const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; + const unsigned char* ep = (const unsigned char*)io->readbuf.base + io->readbuf.tail; + const unsigned char* p = sp; + while (p <= ep) { + if (*p == delim) { + int len = p - sp + 1; + io->readbuf.head += len; + if (io->readbuf.head == io->readbuf.tail) { + io->readbuf.head = io->readbuf.tail = 0; + } + hio_read_cb(io, (void*)sp, len); + return len; + } + ++p; + } + } + io->read_flags = HIO_READ_UNTIL_DELIM; + io->read_until_length = delim; + // NOTE: prepare readbuf + if (hio_is_loop_readbuf(io) || + io->readbuf.len < HLOOP_READ_BUFSIZE) { + hio_alloc_readbuf(io, HLOOP_READ_BUFSIZE); + } + return hio_read_once(io); +} + +int hio_read_remain(hio_t* io) { + int remain = io->readbuf.tail - io->readbuf.head; + if (remain > 0) { + void* buf = io->readbuf.base + io->readbuf.head; + io->readbuf.head = io->readbuf.tail = 0; + hio_read_cb(io, buf, remain); + } + return remain; +} + +//-----------------unpack--------------------------------------------- +void hio_set_unpack(hio_t* io, unpack_setting_t* setting) { + hio_unset_unpack(io); + if (setting == NULL) return; + + io->unpack_setting = setting; + if (io->unpack_setting->package_max_length == 0) { + io->unpack_setting->package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + } + if (io->unpack_setting->mode == UNPACK_BY_FIXED_LENGTH) { + assert(io->unpack_setting->fixed_length != 0 && + io->unpack_setting->fixed_length <= io->unpack_setting->package_max_length); + } + else if (io->unpack_setting->mode == UNPACK_BY_DELIMITER) { + if (io->unpack_setting->delimiter_bytes == 0) { + io->unpack_setting->delimiter_bytes = strlen((char*)io->unpack_setting->delimiter); + } + } + else if (io->unpack_setting->mode == UNPACK_BY_LENGTH_FIELD) { + assert(io->unpack_setting->body_offset >= + io->unpack_setting->length_field_offset + + io->unpack_setting->length_field_bytes); + } + + // NOTE: unpack must have own readbuf + if (io->unpack_setting->mode == UNPACK_BY_FIXED_LENGTH) { + io->readbuf.len = io->unpack_setting->fixed_length; + } else { + io->readbuf.len = MIN(HLOOP_READ_BUFSIZE, io->unpack_setting->package_max_length); + } + io->max_read_bufsize = io->unpack_setting->package_max_length; + hio_alloc_readbuf(io, io->readbuf.len); +} + +void hio_unset_unpack(hio_t* io) { + if (io->unpack_setting) { + io->unpack_setting = NULL; + // NOTE: unpack has own readbuf + hio_free_readbuf(io); + } +} + +//-----------------upstream--------------------------------------------- +void hio_read_upstream(hio_t* io) { + hio_t* upstream_io = io->upstream_io; + if (upstream_io) { + hio_read(io); + hio_read(upstream_io); + } +} + +void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes) { + hio_t* upstream_io = io->upstream_io; + if (upstream_io && hio_write_is_complete(io)) { + hio_setcb_write(io, NULL); + hio_read(upstream_io); + } +} + +void hio_write_upstream(hio_t* io, void* buf, int bytes) { + hio_t* upstream_io = io->upstream_io; + if (upstream_io) { + int nwrite = hio_write(upstream_io, buf, bytes); + // if (!hio_write_is_complete(upstream_io)) { + if (nwrite >= 0 && nwrite < bytes) { + hio_read_stop(io); + hio_setcb_write(upstream_io, hio_read_upstream_on_write_complete); + } + } +} + +void hio_close_upstream(hio_t* io) { + hio_t* upstream_io = io->upstream_io; + if (upstream_io) { + hio_close(upstream_io); + } +} + +void hio_setup_upstream(hio_t* io1, hio_t* io2) { + io1->upstream_io = io2; + io2->upstream_io = io1; +} + +hio_t* hio_get_upstream(hio_t* io) { + return io->upstream_io; +} + +hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl) { + hio_t* upstream_io = hio_create_socket(io->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (upstream_io == NULL) return NULL; + if (ssl) hio_enable_ssl(upstream_io); + hio_setup_upstream(io, upstream_io); + hio_setcb_read(io, hio_write_upstream); + hio_setcb_read(upstream_io, hio_write_upstream); + hio_setcb_close(io, hio_close_upstream); + hio_setcb_close(upstream_io, hio_close_upstream); + hio_setcb_connect(upstream_io, hio_read_upstream); + hio_connect(upstream_io); + return upstream_io; +} + +hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port) { + hio_t* upstream_io = hio_create_socket(io->loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE); + if (upstream_io == NULL) return NULL; + hio_setup_upstream(io, upstream_io); + hio_setcb_read(io, hio_write_upstream); + hio_setcb_read(upstream_io, hio_write_upstream); + hio_read_upstream(io); + return upstream_io; +} diff --git a/external/libhv/libhv-1.3.2/event/hevent.h b/external/libhv/libhv-1.3.2/event/hevent.h new file mode 100644 index 0000000..5fec7c9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/hevent.h @@ -0,0 +1,291 @@ +#ifndef HV_EVENT_H_ +#define HV_EVENT_H_ + +#include "hloop.h" +#include "iowatcher.h" +#include "rudp.h" + +#include "hbuf.h" +#include "hmutex.h" + +#include "array.h" +#include "list.h" +#include "heap.h" +#include "queue.h" + +#define HLOOP_READ_BUFSIZE 8192 // 8K +#define READ_BUFSIZE_HIGH_WATER 65536 // 64K +#define WRITE_BUFSIZE_HIGH_WATER (1U << 23) // 8M +#define MAX_READ_BUFSIZE (1U << 24) // 16M +#define MAX_WRITE_BUFSIZE (1U << 24) // 16M + +// hio_read_flags +#define HIO_READ_ONCE 0x1 +#define HIO_READ_UNTIL_LENGTH 0x2 +#define HIO_READ_UNTIL_DELIM 0x4 + +ARRAY_DECL(hio_t*, io_array); +QUEUE_DECL(hevent_t, event_queue); + +struct hloop_s { + uint32_t flags; + hloop_status_e status; + uint64_t start_ms; // ms + uint64_t start_hrtime; // us + uint64_t end_hrtime; + uint64_t cur_hrtime; + uint64_t loop_cnt; + long pid; + long tid; + void* userdata; +//private: + // events + uint32_t intern_nevents; + uint32_t nactives; + uint32_t npendings; + // pendings: with priority as array.index + hevent_t* pendings[HEVENT_PRIORITY_SIZE]; + // idles + struct list_head idles; + uint32_t nidles; + // timers + struct heap timers; // monotonic time + struct heap realtimers; // realtime + uint32_t ntimers; + // ios: with fd as array.index + struct io_array ios; + uint32_t nios; + // one loop per thread, so one readbuf per loop is OK. + hbuf_t readbuf; + void* iowatcher; + // custom_events + int eventfds[2]; + event_queue custom_events; + hmutex_t custom_events_mutex; +}; + +uint64_t hloop_next_event_id(); + +struct hidle_s { + HEVENT_FIELDS + uint32_t repeat; +//private: + struct list_node node; +}; + +#define HTIMER_FIELDS \ + HEVENT_FIELDS \ + uint32_t repeat; \ + uint64_t next_timeout; \ + struct heap_node node; + +struct htimer_s { + HTIMER_FIELDS +}; + +struct htimeout_s { + HTIMER_FIELDS + uint32_t timeout; \ +}; + +struct hperiod_s { + HTIMER_FIELDS + int8_t minute; + int8_t hour; + int8_t day; + int8_t week; + int8_t month; +}; + +QUEUE_DECL(offset_buf_t, write_queue); +// sizeof(struct hio_s)=416 on linux-x64 +struct hio_s { + HEVENT_FIELDS + // flags + unsigned ready :1; + unsigned connected :1; + unsigned closed :1; + unsigned accept :1; + unsigned connect :1; + unsigned connectex :1; // for ConnectEx/DisconnectEx + unsigned recv :1; + unsigned send :1; + unsigned recvfrom :1; + unsigned sendto :1; + unsigned close :1; + unsigned alloced_readbuf :1; // for hio_alloc_readbuf + unsigned alloced_ssl_ctx :1; // for hio_new_ssl_ctx +// public: + hio_type_e io_type; + uint32_t id; // fd cannot be used as unique identifier, so we provide an id + int fd; + int error; + int events; + int revents; + struct sockaddr* localaddr; + struct sockaddr* peeraddr; + uint64_t last_read_hrtime; + uint64_t last_write_hrtime; + // read + fifo_buf_t readbuf; + unsigned int read_flags; + // for hio_read_until + union { + unsigned int read_until_length; + unsigned char read_until_delim; + }; + uint32_t max_read_bufsize; + uint32_t small_readbytes_cnt; // for readbuf autosize + // write + struct write_queue write_queue; + hrecursive_mutex_t write_mutex; // lock write and write_queue + uint32_t write_bufsize; + uint32_t max_write_bufsize; + // callbacks + hread_cb read_cb; + hwrite_cb write_cb; + hclose_cb close_cb; + haccept_cb accept_cb; + hconnect_cb connect_cb; + // timers + int connect_timeout; // ms + int close_timeout; // ms + int read_timeout; // ms + int write_timeout; // ms + int keepalive_timeout; // ms + int heartbeat_interval; // ms + hio_send_heartbeat_fn heartbeat_fn; + htimer_t* connect_timer; + htimer_t* close_timer; + htimer_t* read_timer; + htimer_t* write_timer; + htimer_t* keepalive_timer; + htimer_t* heartbeat_timer; + // upstream + struct hio_s* upstream_io; // for hio_setup_upstream + // unpack + unpack_setting_t* unpack_setting; // for hio_set_unpack + // ssl + void* ssl; // for hio_set_ssl + void* ssl_ctx; // for hio_set_ssl_ctx + char* hostname; // for hssl_set_sni_hostname + // context + void* ctx; // for hio_context / hio_set_context +// private: +#if defined(EVENT_POLL) || defined(EVENT_KQUEUE) + int event_index[2]; // for poll,kqueue +#endif + +#ifdef EVENT_IOCP + void* hovlp; // for iocp/overlapio +#endif + +#if WITH_RUDP + rudp_t rudp; +#if WITH_KCP + kcp_setting_t* kcp_setting; +#endif +#endif +}; +/* + * hio lifeline: + * + * fd => + * hio_get => HV_ALLOC_SIZEOF(io) => hio_init => hio_ready + * + * hio_read => hio_add(HV_READ) => hio_read_cb + * hio_write => hio_add(HV_WRITE) => hio_write_cb + * hio_close => hio_done => hio_del(HV_RDWR) => hio_close_cb + * + * hloop_stop => hloop_free => hio_free => HV_FREE(io) + */ +void hio_init(hio_t* io); +void hio_ready(hio_t* io); +void hio_done(hio_t* io); +void hio_free(hio_t* io); +uint32_t hio_next_id(); + +void hio_accept_cb(hio_t* io); +void hio_connect_cb(hio_t* io); +void hio_handle_read(hio_t* io, void* buf, int readbytes); +void hio_read_cb(hio_t* io, void* buf, int len); +void hio_write_cb(hio_t* io, const void* buf, int len); +void hio_close_cb(hio_t* io); + +void hio_del_connect_timer(hio_t* io); +void hio_del_close_timer(hio_t* io); +void hio_del_read_timer(hio_t* io); +void hio_del_write_timer(hio_t* io); +void hio_del_keepalive_timer(hio_t* io); +void hio_del_heartbeat_timer(hio_t* io); + +static inline void hio_use_loop_readbuf(hio_t* io) { + hloop_t* loop = io->loop; + if (loop->readbuf.len == 0) { + loop->readbuf.len = HLOOP_READ_BUFSIZE; + HV_ALLOC(loop->readbuf.base, loop->readbuf.len); + } + io->readbuf.base = loop->readbuf.base; + io->readbuf.len = loop->readbuf.len; +} +static inline bool hio_is_loop_readbuf(hio_t* io) { + return io->readbuf.base == io->loop->readbuf.base; +} +static inline bool hio_is_alloced_readbuf(hio_t* io) { + return io->alloced_readbuf; +} +void hio_alloc_readbuf(hio_t* io, int len); +void hio_free_readbuf(hio_t* io); +void hio_memmove_readbuf(hio_t* io); + +#define EVENT_ENTRY(p) container_of(p, hevent_t, pending_node) +#define IDLE_ENTRY(p) container_of(p, hidle_t, node) +#define TIMER_ENTRY(p) container_of(p, htimer_t, node) + +#define EVENT_ACTIVE(ev) \ + if (!ev->active) {\ + ev->active = 1;\ + ev->loop->nactives++;\ + }\ + +#define EVENT_INACTIVE(ev) \ + if (ev->active) {\ + ev->active = 0;\ + ev->loop->nactives--;\ + }\ + +#define EVENT_PENDING(ev) \ + do {\ + if (!ev->pending) {\ + ev->pending = 1;\ + ev->loop->npendings++;\ + hevent_t** phead = &ev->loop->pendings[HEVENT_PRIORITY_INDEX(ev->priority)];\ + ev->pending_next = *phead;\ + *phead = (hevent_t*)ev;\ + }\ + } while(0) + +#define EVENT_ADD(loop, ev, cb) \ + do {\ + ev->loop = loop;\ + ev->event_id = hloop_next_event_id();\ + ev->cb = (hevent_cb)cb;\ + EVENT_ACTIVE(ev);\ + } while(0) + +#define EVENT_DEL(ev) \ + do {\ + EVENT_INACTIVE(ev);\ + if (!ev->pending) {\ + HV_FREE(ev);\ + }\ + } while(0) + +#define EVENT_RESET(ev) \ + do {\ + ev->destroy = 0;\ + EVENT_ACTIVE(ev);\ + ev->pending = 0;\ + } while(0) + +#endif // HV_EVENT_H_ diff --git a/external/libhv/libhv-1.3.2/event/hloop.c b/external/libhv/libhv-1.3.2/event/hloop.c new file mode 100644 index 0000000..9b4ac18 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/hloop.c @@ -0,0 +1,1020 @@ +#include "hloop.h" +#include "hevent.h" +#include "iowatcher.h" + +#include "hdef.h" +#include "hbase.h" +#include "hlog.h" +#include "hmath.h" +#include "htime.h" +#include "hsocket.h" +#include "hthread.h" + +#if defined(OS_UNIX) && HAVE_EVENTFD +#include "sys/eventfd.h" +#endif + +#define HLOOP_PAUSE_TIME 10 // ms +#define HLOOP_MAX_BLOCK_TIME 100 // ms +#define HLOOP_STAT_TIMEOUT 60000 // ms + +#define IO_ARRAY_INIT_SIZE 1024 +#define CUSTOM_EVENT_QUEUE_INIT_SIZE 16 + +#define EVENTFDS_READ_INDEX 0 +#define EVENTFDS_WRITE_INDEX 1 + +static void __hidle_del(hidle_t* idle); +static void __htimer_del(htimer_t* timer); + +static int timers_compare(const struct heap_node* lhs, const struct heap_node* rhs) { + return TIMER_ENTRY(lhs)->next_timeout < TIMER_ENTRY(rhs)->next_timeout; +} + +static int hloop_process_idles(hloop_t* loop) { + int nidles = 0; + struct list_node* node = loop->idles.next; + hidle_t* idle = NULL; + while (node != &loop->idles) { + idle = IDLE_ENTRY(node); + node = node->next; + if (idle->repeat != INFINITE) { + --idle->repeat; + } + if (idle->repeat == 0) { + // NOTE: Just mark it as destroy and remove from list. + // Real deletion occurs after hloop_process_pendings. + __hidle_del(idle); + } + EVENT_PENDING(idle); + ++nidles; + } + return nidles; +} + +static int __hloop_process_timers(struct heap* timers, uint64_t timeout) { + int ntimers = 0; + htimer_t* timer = NULL; + while (timers->root) { + // NOTE: root of minheap has min timeout. + timer = TIMER_ENTRY(timers->root); + if (timer->next_timeout > timeout) { + break; + } + if (timer->repeat != INFINITE) { + --timer->repeat; + } + if (timer->repeat == 0) { + // NOTE: Just mark it as destroy and remove from heap. + // Real deletion occurs after hloop_process_pendings. + __htimer_del(timer); + } + else { + // NOTE: calc next timeout, then re-insert heap. + heap_dequeue(timers); + if (timer->event_type == HEVENT_TYPE_TIMEOUT) { + while (timer->next_timeout <= timeout) { + timer->next_timeout += (uint64_t)((htimeout_t*)timer)->timeout * 1000; + } + } + else if (timer->event_type == HEVENT_TYPE_PERIOD) { + hperiod_t* period = (hperiod_t*)timer; + timer->next_timeout = (uint64_t)cron_next_timeout(period->minute, period->hour, period->day, + period->week, period->month) * 1000000; + } + heap_insert(timers, &timer->node); + } + EVENT_PENDING(timer); + ++ntimers; + } + return ntimers; +} + +static int hloop_process_timers(hloop_t* loop) { + uint64_t now = hloop_now_us(loop); + int ntimers = __hloop_process_timers(&loop->timers, loop->cur_hrtime); + ntimers += __hloop_process_timers(&loop->realtimers, now); + return ntimers; +} + +static int hloop_process_ios(hloop_t* loop, int timeout) { + // That is to call IO multiplexing function such as select, poll, epoll, etc. + int nevents = iowatcher_poll_events(loop, timeout); + if (nevents < 0) { + hlogd("poll_events error=%d", -nevents); + } + return nevents < 0 ? 0 : nevents; +} + +static int hloop_process_pendings(hloop_t* loop) { + if (loop->npendings == 0) return 0; + + hevent_t* cur = NULL; + hevent_t* next = NULL; + int ncbs = 0; + // NOTE: invoke event callback from high to low sorted by priority. + for (int i = HEVENT_PRIORITY_SIZE-1; i >= 0; --i) { + cur = loop->pendings[i]; + while (cur) { + next = cur->pending_next; + if (cur->pending) { + if (cur->active && cur->cb) { + cur->cb(cur); + ++ncbs; + } + cur->pending = 0; + // NOTE: Now we can safely delete event marked as destroy. + if (cur->destroy) { + EVENT_DEL(cur); + } + } + cur = next; + } + loop->pendings[i] = NULL; + } + loop->npendings = 0; + return ncbs; +} + +// hloop_process_ios -> hloop_process_timers -> hloop_process_idles -> hloop_process_pendings +int hloop_process_events(hloop_t* loop, int timeout_ms) { + // ios -> timers -> idles + int nios, ntimers, nidles; + nios = ntimers = nidles = 0; + + // calc blocktime + int32_t blocktime_ms = timeout_ms; + if (loop->ntimers) { + hloop_update_time(loop); + int64_t blocktime_us = blocktime_ms * 1000; + if (loop->timers.root) { + int64_t min_timeout = TIMER_ENTRY(loop->timers.root)->next_timeout - loop->cur_hrtime; + blocktime_us = MIN(blocktime_us, min_timeout); + } + if (loop->realtimers.root) { + int64_t min_timeout = TIMER_ENTRY(loop->realtimers.root)->next_timeout - hloop_now_us(loop); + blocktime_us = MIN(blocktime_us, min_timeout); + } + if (blocktime_us < 0) goto process_timers; + blocktime_ms = blocktime_us / 1000 + 1; + blocktime_ms = MIN(blocktime_ms, timeout_ms); + } + + if (loop->nios) { + nios = hloop_process_ios(loop, blocktime_ms); + } else { + hv_msleep(blocktime_ms); + } + hloop_update_time(loop); + // wakeup by hloop_stop + if (loop->status == HLOOP_STATUS_STOP) { + return 0; + } + +process_timers: + if (loop->ntimers) { + ntimers = hloop_process_timers(loop); + } + + int npendings = loop->npendings; + if (npendings == 0) { + if (loop->nidles) { + nidles= hloop_process_idles(loop); + } + } + int ncbs = hloop_process_pendings(loop); + // printd("blocktime=%d nios=%d/%u ntimers=%d/%u nidles=%d/%u nactives=%d npendings=%d ncbs=%d\n", + // blocktime, nios, loop->nios, ntimers, loop->ntimers, nidles, loop->nidles, + // loop->nactives, npendings, ncbs); + return ncbs; +} + +static void hloop_stat_timer_cb(htimer_t* timer) { + hloop_t* loop = timer->loop; + // hlog_set_level(LOG_LEVEL_DEBUG); + hlogd("[loop] pid=%ld tid=%ld uptime=%lluus cnt=%llu nactives=%u nios=%u ntimers=%u nidles=%u", + loop->pid, loop->tid, + (unsigned long long)loop->cur_hrtime - loop->start_hrtime, + (unsigned long long)loop->loop_cnt, + loop->nactives, loop->nios, loop->ntimers, loop->nidles); +} + +static void eventfd_read_cb(hio_t* io, void* buf, int readbytes) { + hloop_t* loop = io->loop; + hevent_t* pev = NULL; + hevent_t ev; + uint64_t count = readbytes; +#if defined(OS_UNIX) && HAVE_EVENTFD + assert(readbytes == sizeof(count)); + count = *(uint64_t*)buf; +#endif + for (uint64_t i = 0; i < count; ++i) { + hmutex_lock(&loop->custom_events_mutex); + if (event_queue_empty(&loop->custom_events)) { + goto unlock; + } + pev = event_queue_front(&loop->custom_events); + if (pev == NULL) { + goto unlock; + } + ev = *pev; + event_queue_pop_front(&loop->custom_events); + // NOTE: unlock before cb, avoid deadlock if hloop_post_event called in cb. + hmutex_unlock(&loop->custom_events_mutex); + if (ev.cb) { + ev.cb(&ev); + } + } + return; +unlock: + hmutex_unlock(&loop->custom_events_mutex); +} + +static int hloop_create_eventfds(hloop_t* loop) { +#if defined(OS_UNIX) && HAVE_EVENTFD + int efd = eventfd(0, 0); + if (efd < 0) { + hloge("eventfd create failed!"); + return -1; + } + loop->eventfds[0] = loop->eventfds[1] = efd; +#elif defined(OS_UNIX) && HAVE_PIPE + if (pipe(loop->eventfds) != 0) { + hloge("pipe create failed!"); + return -1; + } +#else + if (Socketpair(AF_INET, SOCK_STREAM, 0, loop->eventfds) != 0) { + hloge("socketpair create failed!"); + return -1; + } +#endif + hio_t* io = hread(loop, loop->eventfds[EVENTFDS_READ_INDEX], NULL, 0, eventfd_read_cb); + io->priority = HEVENT_HIGH_PRIORITY; + ++loop->intern_nevents; + return 0; +} + +static void hloop_destroy_eventfds(hloop_t* loop) { +#if defined(OS_UNIX) && HAVE_EVENTFD + // NOTE: eventfd has only one fd + SAFE_CLOSE(loop->eventfds[0]); +#elif defined(OS_UNIX) && HAVE_PIPE + SAFE_CLOSE(loop->eventfds[0]); + SAFE_CLOSE(loop->eventfds[1]); +#else + // NOTE: Avoid duplication closesocket in hio_cleanup + // SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_READ_INDEX]); + SAFE_CLOSESOCKET(loop->eventfds[EVENTFDS_WRITE_INDEX]); +#endif + loop->eventfds[0] = loop->eventfds[1] = -1; +} + +void hloop_post_event(hloop_t* loop, hevent_t* ev) { + if (ev->loop == NULL) { + ev->loop = loop; + } + if (ev->event_type == 0) { + ev->event_type = HEVENT_TYPE_CUSTOM; + } + if (ev->event_id == 0) { + ev->event_id = hloop_next_event_id(); + } + + int nwrite = 0; + uint64_t count = 1; + hmutex_lock(&loop->custom_events_mutex); + if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) { + if (hloop_create_eventfds(loop) != 0) { + goto unlock; + } + } +#if defined(OS_UNIX) && HAVE_EVENTFD + nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], &count, sizeof(count)); +#elif defined(OS_UNIX) && HAVE_PIPE + nwrite = write(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1); +#else + nwrite = send(loop->eventfds[EVENTFDS_WRITE_INDEX], "e", 1, 0); +#endif + if (nwrite <= 0) { + hloge("hloop_post_event failed!"); + goto unlock; + } + if (loop->custom_events.maxsize == 0) { + event_queue_init(&loop->custom_events, CUSTOM_EVENT_QUEUE_INIT_SIZE); + } + event_queue_push_back(&loop->custom_events, ev); +unlock: + hmutex_unlock(&loop->custom_events_mutex); +} + +static void hloop_init(hloop_t* loop) { +#ifdef OS_WIN + WSAInit(); +#endif +#ifdef SIGPIPE + // NOTE: if not ignore SIGPIPE, write twice when peer close will lead to exit process by SIGPIPE. + signal(SIGPIPE, SIG_IGN); +#endif + + loop->status = HLOOP_STATUS_STOP; + loop->pid = hv_getpid(); + loop->tid = hv_gettid(); + + // idles + list_init(&loop->idles); + + // timers + heap_init(&loop->timers, timers_compare); + heap_init(&loop->realtimers, timers_compare); + + // ios + // NOTE: io_array_init when hio_get -> io_array_resize + // io_array_init(&loop->ios, IO_ARRAY_INIT_SIZE); + + // readbuf + // NOTE: alloc readbuf when hio_use_loop_readbuf + // loop->readbuf.len = HLOOP_READ_BUFSIZE; + // HV_ALLOC(loop->readbuf.base, loop->readbuf.len); + + // NOTE: iowatcher_init when hio_add -> iowatcher_add_event + // iowatcher_init(loop); + + // custom_events + hmutex_init(&loop->custom_events_mutex); + // NOTE: hloop_create_eventfds when hloop_post_event or hloop_run + loop->eventfds[0] = loop->eventfds[1] = -1; + + // NOTE: init start_time here, because htimer_add use it. + loop->start_ms = gettimeofday_ms(); + loop->start_hrtime = loop->cur_hrtime = gethrtime_us(); +} + +static void hloop_cleanup(hloop_t* loop) { + // pendings + printd("cleanup pendings...\n"); + for (int i = 0; i < HEVENT_PRIORITY_SIZE; ++i) { + loop->pendings[i] = NULL; + } + + // ios + printd("cleanup ios...\n"); + for (int i = 0; i < loop->ios.maxsize; ++i) { + hio_t* io = loop->ios.ptr[i]; + if (io) { + hio_free(io); + } + } + io_array_cleanup(&loop->ios); + + // idles + printd("cleanup idles...\n"); + struct list_node* node = loop->idles.next; + hidle_t* idle; + while (node != &loop->idles) { + idle = IDLE_ENTRY(node); + node = node->next; + HV_FREE(idle); + } + list_init(&loop->idles); + + // timers + printd("cleanup timers...\n"); + htimer_t* timer; + while (loop->timers.root) { + timer = TIMER_ENTRY(loop->timers.root); + heap_dequeue(&loop->timers); + HV_FREE(timer); + } + heap_init(&loop->timers, NULL); + while (loop->realtimers.root) { + timer = TIMER_ENTRY(loop->realtimers.root); + heap_dequeue(&loop->realtimers); + HV_FREE(timer); + } + heap_init(&loop->realtimers, NULL); + + // readbuf + if (loop->readbuf.base && loop->readbuf.len) { + HV_FREE(loop->readbuf.base); + loop->readbuf.base = NULL; + loop->readbuf.len = 0; + } + + // iowatcher + iowatcher_cleanup(loop); + + // custom_events + hmutex_lock(&loop->custom_events_mutex); + hloop_destroy_eventfds(loop); + event_queue_cleanup(&loop->custom_events); + hmutex_unlock(&loop->custom_events_mutex); + hmutex_destroy(&loop->custom_events_mutex); +} + +hloop_t* hloop_new(int flags) { + hloop_t* loop; + HV_ALLOC_SIZEOF(loop); + hloop_init(loop); + loop->flags |= flags; + return loop; +} + +void hloop_free(hloop_t** pp) { + if (pp && *pp) { + hloop_cleanup(*pp); + HV_FREE(*pp); + *pp = NULL; + } +} + +// while (loop->status) { hloop_process_events(loop); } +int hloop_run(hloop_t* loop) { + if (loop == NULL) return -1; + if (loop->status == HLOOP_STATUS_RUNNING) return -2; + + loop->status = HLOOP_STATUS_RUNNING; + loop->pid = hv_getpid(); + loop->tid = hv_gettid(); + + if (loop->intern_nevents == 0) { + hmutex_lock(&loop->custom_events_mutex); + if (loop->eventfds[EVENTFDS_WRITE_INDEX] == -1) { + hloop_create_eventfds(loop); + } + hmutex_unlock(&loop->custom_events_mutex); + +#ifdef DEBUG + htimer_add(loop, hloop_stat_timer_cb, HLOOP_STAT_TIMEOUT, INFINITE); + ++loop->intern_nevents; +#endif + } + + while (loop->status != HLOOP_STATUS_STOP) { + if (loop->status == HLOOP_STATUS_PAUSE) { + hv_msleep(HLOOP_PAUSE_TIME); + hloop_update_time(loop); + continue; + } + ++loop->loop_cnt; + if ((loop->flags & HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS) && + loop->nactives <= loop->intern_nevents) { + break; + } + hloop_process_events(loop, HLOOP_MAX_BLOCK_TIME); + if (loop->flags & HLOOP_FLAG_RUN_ONCE) { + break; + } + } + + loop->status = HLOOP_STATUS_STOP; + loop->end_hrtime = gethrtime_us(); + + if (loop->flags & HLOOP_FLAG_AUTO_FREE) { + hloop_cleanup(loop); + HV_FREE(loop); + } + return 0; +} + +int hloop_wakeup(hloop_t* loop) { + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + hloop_post_event(loop, &ev); + return 0; +} + +int hloop_stop(hloop_t* loop) { + if (hv_gettid() != loop->tid) { + hloop_wakeup(loop); + } + loop->status = HLOOP_STATUS_STOP; + return 0; +} + +int hloop_pause(hloop_t* loop) { + if (loop->status == HLOOP_STATUS_RUNNING) { + loop->status = HLOOP_STATUS_PAUSE; + } + return 0; +} + +int hloop_resume(hloop_t* loop) { + if (loop->status == HLOOP_STATUS_PAUSE) { + loop->status = HLOOP_STATUS_RUNNING; + } + return 0; +} + +hloop_status_e hloop_status(hloop_t* loop) { + return loop->status; +} + +void hloop_update_time(hloop_t* loop) { + loop->cur_hrtime = gethrtime_us(); + if (hloop_now(loop) != time(NULL)) { + // systemtime changed, we adjust start_ms + loop->start_ms = gettimeofday_ms() - (loop->cur_hrtime - loop->start_hrtime) / 1000; + } +} + +uint64_t hloop_now(hloop_t* loop) { + return loop->start_ms / 1000 + (loop->cur_hrtime - loop->start_hrtime) / 1000000; +} + +uint64_t hloop_now_ms(hloop_t* loop) { + return loop->start_ms + (loop->cur_hrtime - loop->start_hrtime) / 1000; +} + +uint64_t hloop_now_us(hloop_t* loop) { + return loop->start_ms * 1000 + (loop->cur_hrtime - loop->start_hrtime); +} + +uint64_t hloop_now_hrtime(hloop_t* loop) { + return loop->cur_hrtime; +} + +uint64_t hio_last_read_time(hio_t* io) { + hloop_t* loop = io->loop; + return loop->start_ms + (io->last_read_hrtime - loop->start_hrtime) / 1000; +} + +uint64_t hio_last_write_time(hio_t* io) { + hloop_t* loop = io->loop; + return loop->start_ms + (io->last_write_hrtime - loop->start_hrtime) / 1000; +} + +long hloop_pid(hloop_t* loop) { + return loop->pid; +} + +long hloop_tid(hloop_t* loop) { + return loop->tid; +} + +uint64_t hloop_count(hloop_t* loop) { + return loop->loop_cnt; +} + +uint32_t hloop_nios(hloop_t* loop) { + return loop->nios; +} + +uint32_t hloop_ntimers(hloop_t* loop) { + return loop->ntimers; +} + +uint32_t hloop_nidles(hloop_t* loop) { + return loop->nidles; +} + +uint32_t hloop_nactives(hloop_t* loop) { + return loop->nactives; +} + +void hloop_set_userdata(hloop_t* loop, void* userdata) { + loop->userdata = userdata; +} + +void* hloop_userdata(hloop_t* loop) { + return loop->userdata; +} + +hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat) { + hidle_t* idle; + HV_ALLOC_SIZEOF(idle); + idle->event_type = HEVENT_TYPE_IDLE; + idle->priority = HEVENT_LOWEST_PRIORITY; + idle->repeat = repeat; + list_add(&idle->node, &loop->idles); + EVENT_ADD(loop, idle, cb); + loop->nidles++; + return idle; +} + +static void __hidle_del(hidle_t* idle) { + if (idle->destroy) return; + idle->destroy = 1; + list_del(&idle->node); + idle->loop->nidles--; +} + +void hidle_del(hidle_t* idle) { + if (!idle->active) return; + __hidle_del(idle); + EVENT_DEL(idle); +} + +htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat) { + if (timeout_ms == 0) return NULL; + htimeout_t* timer; + HV_ALLOC_SIZEOF(timer); + timer->event_type = HEVENT_TYPE_TIMEOUT; + timer->priority = HEVENT_HIGHEST_PRIORITY; + timer->repeat = repeat; + timer->timeout = timeout_ms; + hloop_update_time(loop); + timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout_ms * 1000; + // NOTE: Limit granularity to 100ms + if (timeout_ms >= 1000 && timeout_ms % 100 == 0) { + timer->next_timeout = timer->next_timeout / 100000 * 100000; + } + heap_insert(&loop->timers, &timer->node); + EVENT_ADD(loop, timer, cb); + loop->ntimers++; + return (htimer_t*)timer; +} + +void htimer_reset(htimer_t* timer, uint32_t timeout_ms) { + if (timer->event_type != HEVENT_TYPE_TIMEOUT) { + return; + } + hloop_t* loop = timer->loop; + htimeout_t* timeout = (htimeout_t*)timer; + if (timer->destroy) { + loop->ntimers++; + } else { + heap_remove(&loop->timers, &timer->node); + } + if (timer->repeat == 0) { + timer->repeat = 1; + } + if (timeout_ms > 0) { + timeout->timeout = timeout_ms; + } + timer->next_timeout = loop->cur_hrtime + (uint64_t)timeout->timeout * 1000; + // NOTE: Limit granularity to 100ms + if (timeout->timeout >= 1000 && timeout->timeout % 100 == 0) { + timer->next_timeout = timer->next_timeout / 100000 * 100000; + } + heap_insert(&loop->timers, &timer->node); + EVENT_RESET(timer); +} + +htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, + int8_t minute, int8_t hour, int8_t day, + int8_t week, int8_t month, uint32_t repeat) { + if (minute > 59 || hour > 23 || day > 31 || week > 6 || month > 12) { + return NULL; + } + hperiod_t* timer; + HV_ALLOC_SIZEOF(timer); + timer->event_type = HEVENT_TYPE_PERIOD; + timer->priority = HEVENT_HIGH_PRIORITY; + timer->repeat = repeat; + timer->minute = minute; + timer->hour = hour; + timer->day = day; + timer->month = month; + timer->week = week; + timer->next_timeout = (uint64_t)cron_next_timeout(minute, hour, day, week, month) * 1000000; + heap_insert(&loop->realtimers, &timer->node); + EVENT_ADD(loop, timer, cb); + loop->ntimers++; + return (htimer_t*)timer; +} + +static void __htimer_del(htimer_t* timer) { + if (timer->destroy) return; + if (timer->event_type == HEVENT_TYPE_TIMEOUT) { + heap_remove(&timer->loop->timers, &timer->node); + } else if (timer->event_type == HEVENT_TYPE_PERIOD) { + heap_remove(&timer->loop->realtimers, &timer->node); + } + timer->loop->ntimers--; + timer->destroy = 1; +} + +void htimer_del(htimer_t* timer) { + if (!timer->active) return; + __htimer_del(timer); + EVENT_DEL(timer); +} + +const char* hio_engine() { +#ifdef EVENT_SELECT + return "select"; +#elif defined(EVENT_POLL) + return "poll"; +#elif defined(EVENT_EPOLL) + return "epoll"; +#elif defined(EVENT_KQUEUE) + return "kqueue"; +#elif defined(EVENT_IOCP) + return "iocp"; +#elif defined(EVENT_PORT) + return "evport"; +#else + return "noevent"; +#endif +} + +static inline hio_t* __hio_get(hloop_t* loop, int fd) { + if (fd >= loop->ios.maxsize) { + int newsize = ceil2e(fd); + newsize = MAX(newsize, IO_ARRAY_INIT_SIZE); + io_array_resize(&loop->ios, newsize > fd ? newsize : 2*fd); + } + return loop->ios.ptr[fd]; +} + +hio_t* hio_get(hloop_t* loop, int fd) { + hio_t* io = __hio_get(loop, fd); + if (io == NULL) { + HV_ALLOC_SIZEOF(io); + hio_init(io); + io->event_type = HEVENT_TYPE_IO; + io->loop = loop; + io->fd = fd; + loop->ios.ptr[fd] = io; + } + + if (!io->ready) { + hio_ready(io); + } + + return io; +} + +void hio_detach(hio_t* io) { + hloop_t* loop = io->loop; + int fd = io->fd; + assert(loop != NULL && fd < loop->ios.maxsize); + loop->ios.ptr[fd] = NULL; +} + +void hio_attach(hloop_t* loop, hio_t* io) { + int fd = io->fd; + // NOTE: hio was not freed for reused when closed, but attached hio can't be reused, + // so we need to free it if fd exists to avoid memory leak. + hio_t* preio = __hio_get(loop, fd); + if (preio != NULL && preio != io) { + hio_free(preio); + } + + io->loop = loop; + // NOTE: use new_loop readbuf + hio_use_loop_readbuf(io); + loop->ios.ptr[fd] = io; +} + +bool hio_exists(hloop_t* loop, int fd) { + if (fd >= loop->ios.maxsize) { + return false; + } + return loop->ios.ptr[fd] != NULL; +} + +int hio_add(hio_t* io, hio_cb cb, int events) { + printd("hio_add fd=%d io->events=%d events=%d\n", io->fd, io->events, events); +#ifdef OS_WIN + // Windows iowatcher not work on stdio + if (io->fd < 3) return -1; +#endif + hloop_t* loop = io->loop; + if (!io->active) { + EVENT_ADD(loop, io, cb); + loop->nios++; + } + + if (!io->ready) { + hio_ready(io); + } + + if (cb) { + io->cb = (hevent_cb)cb; + } + + if (!(io->events & events)) { + iowatcher_add_event(loop, io->fd, events); + io->events |= events; + } + return 0; +} + +int hio_del(hio_t* io, int events) { + printd("hio_del fd=%d io->events=%d events=%d\n", io->fd, io->events, events); +#ifdef OS_WIN + // Windows iowatcher not work on stdio + if (io->fd < 3) return -1; +#endif + if (!io->active) return -1; + + if (io->events & events) { + iowatcher_del_event(io->loop, io->fd, events); + io->events &= ~events; + } + if (io->events == 0) { + io->loop->nios--; + // NOTE: not EVENT_DEL, avoid free + EVENT_INACTIVE(io); + } + return 0; +} + +static void hio_close_event_cb(hevent_t* ev) { + hio_t* io = (hio_t*)ev->userdata; + uint32_t id = (uintptr_t)ev->privdata; + if (io->id != id) return; + hio_close(io); +} + +int hio_close_async(hio_t* io) { + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.cb = hio_close_event_cb; + ev.userdata = io; + ev.privdata = (void*)(uintptr_t)io->id; + hloop_post_event(io->loop, &ev); + return 0; +} + +//------------------high-level apis------------------------------------------- +hio_t* hread(hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb) { + hio_t* io = hio_get(loop, fd); + assert(io != NULL); + if (buf && len) { + io->readbuf.base = (char*)buf; + io->readbuf.len = len; + } + if (read_cb) { + io->read_cb = read_cb; + } + hio_read(io); + return io; +} + +hio_t* hwrite(hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb) { + hio_t* io = hio_get(loop, fd); + assert(io != NULL); + if (write_cb) { + io->write_cb = write_cb; + } + hio_write(io, buf, len); + return io; +} + +hio_t* haccept(hloop_t* loop, int listenfd, haccept_cb accept_cb) { + hio_t* io = hio_get(loop, listenfd); + assert(io != NULL); + if (accept_cb) { + io->accept_cb = accept_cb; + } + if (hio_accept(io) != 0) return NULL; + return io; +} + +hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb) { + hio_t* io = hio_get(loop, connfd); + assert(io != NULL); + if (connect_cb) { + io->connect_cb = connect_cb; + } + if (hio_connect(io) != 0) return NULL; + return io; +} + +void hclose (hloop_t* loop, int fd) { + hio_t* io = hio_get(loop, fd); + assert(io != NULL); + hio_close(io); +} + +hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb) { + //hio_t* io = hio_get(loop, connfd); + //assert(io != NULL); + //io->recv = 1; + //if (io->io_type != HIO_TYPE_SSL) { + //io->io_type = HIO_TYPE_TCP; + //} + return hread(loop, connfd, buf, len, read_cb); +} + +hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb) { + //hio_t* io = hio_get(loop, connfd); + //assert(io != NULL); + //io->send = 1; + //if (io->io_type != HIO_TYPE_SSL) { + //io->io_type = HIO_TYPE_TCP; + //} + return hwrite(loop, connfd, buf, len, write_cb); +} + +hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb) { + //hio_t* io = hio_get(loop, sockfd); + //assert(io != NULL); + //io->recvfrom = 1; + //io->io_type = HIO_TYPE_UDP; + return hread(loop, sockfd, buf, len, read_cb); +} + +hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb) { + //hio_t* io = hio_get(loop, sockfd); + //assert(io != NULL); + //io->sendto = 1; + //io->io_type = HIO_TYPE_UDP; + return hwrite(loop, sockfd, buf, len, write_cb); +} + +//-----------------top-level apis--------------------------------------------- +hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, hio_type_e type, hio_side_e side) { + int sock_type = (type & HIO_TYPE_SOCK_STREAM) ? SOCK_STREAM : + (type & HIO_TYPE_SOCK_DGRAM) ? SOCK_DGRAM : + (type & HIO_TYPE_SOCK_RAW) ? SOCK_RAW : -1; + if (sock_type == -1) return NULL; + sockaddr_u addr; + memset(&addr, 0, sizeof(addr)); + int ret = -1; +#ifdef ENABLE_UDS + if (port < 0) { + sockaddr_set_path(&addr, host); + ret = 0; + } +#endif + if (port >= 0) { + ret = sockaddr_set_ipport(&addr, host, port); + } + if (ret != 0) { + // fprintf(stderr, "unknown host: %s\n", host); + return NULL; + } + int sockfd = socket(addr.sa.sa_family, sock_type, 0); + if (sockfd < 0) { + perror("socket"); + return NULL; + } + hio_t* io = NULL; + if (side == HIO_SERVER_SIDE) { +#ifdef OS_UNIX + so_reuseaddr(sockfd, 1); + // so_reuseport(sockfd, 1); +#endif + if (addr.sa.sa_family == AF_INET6) { + ip_v6only(sockfd, 0); + } + if (bind(sockfd, &addr.sa, sockaddr_len(&addr)) < 0) { + perror("bind"); + closesocket(sockfd); + return NULL; + } + if (sock_type == SOCK_STREAM) { + if (listen(sockfd, SOMAXCONN) < 0) { + perror("listen"); + closesocket(sockfd); + return NULL; + } + } + } + io = hio_get(loop, sockfd); + assert(io != NULL); + io->io_type = type; + if (side == HIO_SERVER_SIDE) { + hio_set_localaddr(io, &addr.sa, sockaddr_len(&addr)); + io->priority = HEVENT_HIGH_PRIORITY; + } else { + hio_set_peeraddr(io, &addr.sa, sockaddr_len(&addr)); + } + return io; +} + +hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) { + hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE); + if (io == NULL) return NULL; + hio_setcb_accept(io, accept_cb); + if (hio_accept(io) != 0) return NULL; + return io; +} + +hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) { + hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (io == NULL) return NULL; + hio_setcb_connect(io, connect_cb); + hio_setcb_close(io, close_cb); + if (hio_connect(io) != 0) return NULL; + return io; +} + +hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb) { + hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE); + if (io == NULL) return NULL; + hio_setcb_accept(io, accept_cb); + if (hio_accept(io) != 0) return NULL; + return io; +} + +hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb) { + hio_t* io = hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE); + if (io == NULL) return NULL; + hio_setcb_connect(io, connect_cb); + hio_setcb_close(io, close_cb); + if (hio_connect(io) != 0) return NULL; + return io; +} + +hio_t* hloop_create_udp_server(hloop_t* loop, const char* host, int port) { + return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE); +} + +hio_t* hloop_create_udp_client(hloop_t* loop, const char* host, int port) { + return hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE); +} diff --git a/external/libhv/libhv-1.3.2/event/hloop.h b/external/libhv/libhv-1.3.2/event/hloop.h new file mode 100644 index 0000000..be70cfd --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/hloop.h @@ -0,0 +1,745 @@ +#ifndef HV_LOOP_H_ +#define HV_LOOP_H_ + +#include "hexport.h" +#include "hplatform.h" +#include "hdef.h" +#include "hssl.h" + +typedef struct hloop_s hloop_t; +typedef struct hevent_s hevent_t; + +// NOTE: The following structures are subclasses of hevent_t, +// inheriting hevent_t data members and function members. +typedef struct hidle_s hidle_t; +typedef struct htimer_s htimer_t; +typedef struct htimeout_s htimeout_t; +typedef struct hperiod_s hperiod_t; +typedef struct hio_s hio_t; + +typedef void (*hevent_cb) (hevent_t* ev); +typedef void (*hidle_cb) (hidle_t* idle); +typedef void (*htimer_cb) (htimer_t* timer); +typedef void (*hio_cb) (hio_t* io); + +typedef void (*haccept_cb) (hio_t* io); +typedef void (*hconnect_cb) (hio_t* io); +typedef void (*hread_cb) (hio_t* io, void* buf, int readbytes); +typedef void (*hwrite_cb) (hio_t* io, const void* buf, int writebytes); +typedef void (*hclose_cb) (hio_t* io); + +typedef enum { + HLOOP_STATUS_STOP, + HLOOP_STATUS_RUNNING, + HLOOP_STATUS_PAUSE +} hloop_status_e; + +typedef enum { + HEVENT_TYPE_NONE = 0, + HEVENT_TYPE_IO = 0x00000001, + HEVENT_TYPE_TIMEOUT = 0x00000010, + HEVENT_TYPE_PERIOD = 0x00000020, + HEVENT_TYPE_TIMER = HEVENT_TYPE_TIMEOUT|HEVENT_TYPE_PERIOD, + HEVENT_TYPE_IDLE = 0x00000100, + HEVENT_TYPE_CUSTOM = 0x00000400, // 1024 +} hevent_type_e; + +#define HEVENT_LOWEST_PRIORITY (-5) +#define HEVENT_LOW_PRIORITY (-3) +#define HEVENT_NORMAL_PRIORITY 0 +#define HEVENT_HIGH_PRIORITY 3 +#define HEVENT_HIGHEST_PRIORITY 5 +#define HEVENT_PRIORITY_SIZE (HEVENT_HIGHEST_PRIORITY-HEVENT_LOWEST_PRIORITY+1) +#define HEVENT_PRIORITY_INDEX(priority) (priority-HEVENT_LOWEST_PRIORITY) + +#define HEVENT_FLAGS \ + unsigned destroy :1; \ + unsigned active :1; \ + unsigned pending :1; + +#define HEVENT_FIELDS \ + hloop_t* loop; \ + hevent_type_e event_type; \ + uint64_t event_id; \ + hevent_cb cb; \ + void* userdata; \ + void* privdata; \ + struct hevent_s* pending_next; \ + int priority; \ + HEVENT_FLAGS + +// sizeof(struct hevent_s)=64 on x64 +struct hevent_s { + HEVENT_FIELDS +}; + +#define hevent_set_id(ev, id) ((hevent_t*)(ev))->event_id = id +#define hevent_set_cb(ev, cb) ((hevent_t*)(ev))->cb = cb +#define hevent_set_priority(ev, prio) ((hevent_t*)(ev))->priority = prio +#define hevent_set_userdata(ev, udata) ((hevent_t*)(ev))->userdata = (void*)udata + +#define hevent_loop(ev) (((hevent_t*)(ev))->loop) +#define hevent_type(ev) (((hevent_t*)(ev))->event_type) +#define hevent_id(ev) (((hevent_t*)(ev))->event_id) +#define hevent_cb(ev) (((hevent_t*)(ev))->cb) +#define hevent_priority(ev) (((hevent_t*)(ev))->priority) +#define hevent_userdata(ev) (((hevent_t*)(ev))->userdata) + +typedef enum { + HIO_TYPE_UNKNOWN = 0, + HIO_TYPE_STDIN = 0x00000001, + HIO_TYPE_STDOUT = 0x00000002, + HIO_TYPE_STDERR = 0x00000004, + HIO_TYPE_STDIO = 0x0000000F, + + HIO_TYPE_FILE = 0x00000010, + + HIO_TYPE_IP = 0x00000100, + HIO_TYPE_SOCK_RAW = 0x00000F00, + + HIO_TYPE_UDP = 0x00001000, + HIO_TYPE_KCP = 0x00002000, + HIO_TYPE_DTLS = 0x00010000, + HIO_TYPE_SOCK_DGRAM = 0x000FF000, + + HIO_TYPE_TCP = 0x00100000, + HIO_TYPE_SSL = 0x01000000, + HIO_TYPE_TLS = HIO_TYPE_SSL, + HIO_TYPE_SOCK_STREAM= 0x0FF00000, + + HIO_TYPE_SOCKET = 0x0FFFFF00, +} hio_type_e; + +typedef enum { + HIO_SERVER_SIDE = 0, + HIO_CLIENT_SIDE = 1, +} hio_side_e; + +#define HIO_DEFAULT_CONNECT_TIMEOUT 10000 // ms +#define HIO_DEFAULT_CLOSE_TIMEOUT 60000 // ms +#define HIO_DEFAULT_KEEPALIVE_TIMEOUT 75000 // ms +#define HIO_DEFAULT_HEARTBEAT_INTERVAL 10000 // ms + +BEGIN_EXTERN_C + +// loop +#define HLOOP_FLAG_RUN_ONCE 0x00000001 +#define HLOOP_FLAG_AUTO_FREE 0x00000002 +#define HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS 0x00000004 +HV_EXPORT hloop_t* hloop_new(int flags DEFAULT(HLOOP_FLAG_AUTO_FREE)); + +// WARN: Forbid to call hloop_free if HLOOP_FLAG_AUTO_FREE set. +HV_EXPORT void hloop_free(hloop_t** pp); + +HV_EXPORT int hloop_process_events(hloop_t* loop, int timeout_ms DEFAULT(0)); + +// NOTE: when no active events, loop will quit if HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS set. +HV_EXPORT int hloop_run(hloop_t* loop); +// NOTE: hloop_stop called in loop-thread just set flag to quit in next loop, +// if called in other thread, it will wakeup loop-thread from blocking poll system call, +// then you should join loop thread to safely exit loop thread. +HV_EXPORT int hloop_stop(hloop_t* loop); +HV_EXPORT int hloop_pause(hloop_t* loop); +HV_EXPORT int hloop_resume(hloop_t* loop); +HV_EXPORT int hloop_wakeup(hloop_t* loop); +HV_EXPORT hloop_status_e hloop_status(hloop_t* loop); + +HV_EXPORT void hloop_update_time(hloop_t* loop); +HV_EXPORT uint64_t hloop_now(hloop_t* loop); // s +HV_EXPORT uint64_t hloop_now_ms(hloop_t* loop); // ms +HV_EXPORT uint64_t hloop_now_us(hloop_t* loop); // us +HV_EXPORT uint64_t hloop_now_hrtime(hloop_t* loop); // us + +// export some hloop's members +// @return pid of hloop_run +HV_EXPORT long hloop_pid(hloop_t* loop); +// @return tid of hloop_run +HV_EXPORT long hloop_tid(hloop_t* loop); +// @return count of loop +HV_EXPORT uint64_t hloop_count(hloop_t* loop); +// @return number of ios +HV_EXPORT uint32_t hloop_nios(hloop_t* loop); +// @return number of timers +HV_EXPORT uint32_t hloop_ntimers(hloop_t* loop); +// @return number of idles +HV_EXPORT uint32_t hloop_nidles(hloop_t* loop); +// @return number of active events +HV_EXPORT uint32_t hloop_nactives(hloop_t* loop); + +// userdata +HV_EXPORT void hloop_set_userdata(hloop_t* loop, void* userdata); +HV_EXPORT void* hloop_userdata(hloop_t* loop); + +// custom_event +/* + * hevent_t ev; + * memset(&ev, 0, sizeof(hevent_t)); + * ev.event_type = (hevent_type_e)(HEVENT_TYPE_CUSTOM + 1); + * ev.cb = custom_event_cb; + * ev.userdata = userdata; + * hloop_post_event(loop, &ev); + */ +// NOTE: hloop_post_event is thread-safe, used to post event from other thread to loop thread. +HV_EXPORT void hloop_post_event(hloop_t* loop, hevent_t* ev); + +// idle +HV_EXPORT hidle_t* hidle_add(hloop_t* loop, hidle_cb cb, uint32_t repeat DEFAULT(INFINITE)); +HV_EXPORT void hidle_del(hidle_t* idle); + +// timer +HV_EXPORT htimer_t* htimer_add(hloop_t* loop, htimer_cb cb, uint32_t timeout_ms, uint32_t repeat DEFAULT(INFINITE)); +/* + * minute hour day week month cb + * 0~59 0~23 1~31 0~6 1~12 + * -1 -1 -1 -1 -1 cron.minutely + * 30 -1 -1 -1 -1 cron.hourly + * 30 1 -1 -1 -1 cron.daily + * 30 1 15 -1 -1 cron.monthly + * 30 1 -1 5 -1 cron.weekly + * 30 1 1 -1 10 cron.yearly + */ +HV_EXPORT htimer_t* htimer_add_period(hloop_t* loop, htimer_cb cb, + int8_t minute DEFAULT(0), int8_t hour DEFAULT(-1), int8_t day DEFAULT(-1), + int8_t week DEFAULT(-1), int8_t month DEFAULT(-1), uint32_t repeat DEFAULT(INFINITE)); + +HV_EXPORT void htimer_del(htimer_t* timer); +HV_EXPORT void htimer_reset(htimer_t* timer, uint32_t timeout_ms DEFAULT(0)); + +// io +//-----------------------low-level apis--------------------------------------- +#define HV_READ 0x0001 +#define HV_WRITE 0x0004 +#define HV_RDWR (HV_READ|HV_WRITE) +/* +const char* hio_engine() { +#ifdef EVENT_SELECT + return "select"; +#elif defined(EVENT_POLL) + return "poll"; +#elif defined(EVENT_EPOLL) + return "epoll"; +#elif defined(EVENT_KQUEUE) + return "kqueue"; +#elif defined(EVENT_IOCP) + return "iocp"; +#elif defined(EVENT_PORT) + return "evport"; +#else + return "noevent"; +#endif +} +*/ +HV_EXPORT const char* hio_engine(); + +HV_EXPORT hio_t* hio_get(hloop_t* loop, int fd); +HV_EXPORT int hio_add(hio_t* io, hio_cb cb, int events DEFAULT(HV_READ)); +HV_EXPORT int hio_del(hio_t* io, int events DEFAULT(HV_RDWR)); + +// NOTE: io detach from old loop and attach to new loop +/* @see examples/multi-thread/one-acceptor-multi-workers.c +void new_conn_event(hevent_t* ev) { + hloop_t* loop = ev->loop; + hio_t* io = (hio_t*)hevent_userdata(ev); + hio_attach(loop, io); +} + +void on_accpet(hio_t* io) { + hio_detach(io); + + hloop_t* worker_loop = get_one_loop(); + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.loop = worker_loop; + ev.cb = new_conn_event; + ev.userdata = io; + hloop_post_event(worker_loop, &ev); +} + */ +HV_EXPORT void hio_detach(/*hloop_t* loop,*/ hio_t* io); +HV_EXPORT void hio_attach(hloop_t* loop, hio_t* io); +HV_EXPORT bool hio_exists(hloop_t* loop, int fd); + +// hio_t fields +// NOTE: fd cannot be used as unique identifier, so we provide an id. +HV_EXPORT uint32_t hio_id (hio_t* io); +HV_EXPORT int hio_fd (hio_t* io); +HV_EXPORT int hio_error (hio_t* io); +HV_EXPORT int hio_events (hio_t* io); +HV_EXPORT int hio_revents (hio_t* io); +HV_EXPORT hio_type_e hio_type (hio_t* io); +HV_EXPORT struct sockaddr* hio_localaddr(hio_t* io); +HV_EXPORT struct sockaddr* hio_peeraddr (hio_t* io); +HV_EXPORT void hio_set_context(hio_t* io, void* ctx); +HV_EXPORT void* hio_context(hio_t* io); +HV_EXPORT bool hio_is_opened(hio_t* io); +HV_EXPORT bool hio_is_connected(hio_t* io); +HV_EXPORT bool hio_is_closed(hio_t* io); + +// iobuf +// #include "hbuf.h" +typedef struct fifo_buf_s hio_readbuf_t; +// NOTE: One loop per thread, one readbuf per loop. +// But you can pass in your own readbuf instead of the default readbuf to avoid memcopy. +HV_EXPORT void hio_set_readbuf(hio_t* io, void* buf, size_t len); +HV_EXPORT hio_readbuf_t* hio_get_readbuf(hio_t* io); +HV_EXPORT void hio_set_max_read_bufsize (hio_t* io, uint32_t size); +HV_EXPORT void hio_set_max_write_bufsize(hio_t* io, uint32_t size); +// NOTE: hio_write is non-blocking, so there is a write queue inside hio_t to cache unwritten data and wait for writable. +// @return current buffer size of write queue. +HV_EXPORT size_t hio_write_bufsize(hio_t* io); +#define hio_write_is_complete(io) (hio_write_bufsize(io) == 0) + +HV_EXPORT uint64_t hio_last_read_time(hio_t* io); // ms +HV_EXPORT uint64_t hio_last_write_time(hio_t* io); // ms + +// set callbacks +HV_EXPORT void hio_setcb_accept (hio_t* io, haccept_cb accept_cb); +HV_EXPORT void hio_setcb_connect (hio_t* io, hconnect_cb connect_cb); +HV_EXPORT void hio_setcb_read (hio_t* io, hread_cb read_cb); +HV_EXPORT void hio_setcb_write (hio_t* io, hwrite_cb write_cb); +HV_EXPORT void hio_setcb_close (hio_t* io, hclose_cb close_cb); +// get callbacks +HV_EXPORT haccept_cb hio_getcb_accept(hio_t* io); +HV_EXPORT hconnect_cb hio_getcb_connect(hio_t* io); +HV_EXPORT hread_cb hio_getcb_read(hio_t* io); +HV_EXPORT hwrite_cb hio_getcb_write(hio_t* io); +HV_EXPORT hclose_cb hio_getcb_close(hio_t* io); + +// Enable SSL/TLS is so easy :) +HV_EXPORT int hio_enable_ssl(hio_t* io); +HV_EXPORT bool hio_is_ssl(hio_t* io); +HV_EXPORT int hio_set_ssl (hio_t* io, hssl_t ssl); +HV_EXPORT int hio_set_ssl_ctx(hio_t* io, hssl_ctx_t ssl_ctx); +// hssl_ctx_new(opt) -> hio_set_ssl_ctx +HV_EXPORT int hio_new_ssl_ctx(hio_t* io, hssl_ctx_opt_t* opt); +HV_EXPORT hssl_t hio_get_ssl(hio_t* io); +HV_EXPORT hssl_ctx_t hio_get_ssl_ctx(hio_t* io); +// for hssl_set_sni_hostname +HV_EXPORT int hio_set_hostname(hio_t* io, const char* hostname); +HV_EXPORT const char* hio_get_hostname(hio_t* io); + +// connect timeout => hclose_cb +HV_EXPORT void hio_set_connect_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CONNECT_TIMEOUT)); +// close timeout => hclose_cb +HV_EXPORT void hio_set_close_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_CLOSE_TIMEOUT)); +// read timeout => hclose_cb +HV_EXPORT void hio_set_read_timeout(hio_t* io, int timeout_ms); +// write timeout => hclose_cb +HV_EXPORT void hio_set_write_timeout(hio_t* io, int timeout_ms); +// keepalive timeout => hclose_cb +HV_EXPORT void hio_set_keepalive_timeout(hio_t* io, int timeout_ms DEFAULT(HIO_DEFAULT_KEEPALIVE_TIMEOUT)); +/* +void send_heartbeat(hio_t* io) { + static char buf[] = "PING\r\n"; + hio_write(io, buf, 6); +} +hio_set_heartbeat(io, 3000, send_heartbeat); +*/ +typedef void (*hio_send_heartbeat_fn)(hio_t* io); +// heartbeat interval => hio_send_heartbeat_fn +HV_EXPORT void hio_set_heartbeat(hio_t* io, int interval_ms, hio_send_heartbeat_fn fn); + +// Nonblocking, poll IO events in the loop to call corresponding callback. +// hio_add(io, HV_READ) => accept => haccept_cb +HV_EXPORT int hio_accept (hio_t* io); + +// connect => hio_add(io, HV_WRITE) => hconnect_cb +HV_EXPORT int hio_connect(hio_t* io); + +// hio_add(io, HV_READ) => read => hread_cb +HV_EXPORT int hio_read (hio_t* io); +#define hio_read_start(io) hio_read(io) +#define hio_read_stop(io) hio_del(io, HV_READ) + +// hio_read_start => hread_cb => hio_read_stop +HV_EXPORT int hio_read_once (hio_t* io); +// hio_read_once => hread_cb(len) +HV_EXPORT int hio_read_until_length(hio_t* io, unsigned int len); +// hio_read_once => hread_cb(...delim) +HV_EXPORT int hio_read_until_delim (hio_t* io, unsigned char delim); +HV_EXPORT int hio_read_remain(hio_t* io); +// @see examples/tinyhttpd.c examples/tinyproxyd.c +#define hio_readline(io) hio_read_until_delim(io, '\n') +#define hio_readstring(io) hio_read_until_delim(io, '\0') +#define hio_readbytes(io, len) hio_read_until_length(io, len) +#define hio_read_until(io, len) hio_read_until_length(io, len) + +// NOTE: hio_write is thread-safe, locked by recursive_mutex, allow to be called by other threads. +// hio_try_write => hio_add(io, HV_WRITE) => write => hwrite_cb +HV_EXPORT int hio_write (hio_t* io, const void* buf, size_t len); + +// NOTE: hio_close is thread-safe, hio_close_async will be called actually in other thread. +// hio_del(io, HV_RDWR) => close => hclose_cb +HV_EXPORT int hio_close (hio_t* io); +// NOTE: hloop_post_event(hio_close_event) +HV_EXPORT int hio_close_async(hio_t* io); + +//------------------high-level apis------------------------------------------- +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +HV_EXPORT hio_t* hread (hloop_t* loop, int fd, void* buf, size_t len, hread_cb read_cb); +// hio_get -> hio_setcb_write -> hio_write +HV_EXPORT hio_t* hwrite (hloop_t* loop, int fd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); +// hio_get -> hio_close +HV_EXPORT void hclose (hloop_t* loop, int fd); + +// tcp +// hio_get -> hio_setcb_accept -> hio_accept +HV_EXPORT hio_t* haccept (hloop_t* loop, int listenfd, haccept_cb accept_cb); +// hio_get -> hio_setcb_connect -> hio_connect +HV_EXPORT hio_t* hconnect (hloop_t* loop, int connfd, hconnect_cb connect_cb); +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +HV_EXPORT hio_t* hrecv (hloop_t* loop, int connfd, void* buf, size_t len, hread_cb read_cb); +// hio_get -> hio_setcb_write -> hio_write +HV_EXPORT hio_t* hsend (hloop_t* loop, int connfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); + +// udp +HV_EXPORT void hio_set_type(hio_t* io, hio_type_e type); +HV_EXPORT void hio_set_localaddr(hio_t* io, struct sockaddr* addr, int addrlen); +HV_EXPORT void hio_set_peeraddr (hio_t* io, struct sockaddr* addr, int addrlen); +// NOTE: must call hio_set_peeraddr before hrecvfrom/hsendto +// hio_get -> hio_set_readbuf -> hio_setcb_read -> hio_read +HV_EXPORT hio_t* hrecvfrom (hloop_t* loop, int sockfd, void* buf, size_t len, hread_cb read_cb); +// hio_get -> hio_setcb_write -> hio_write +HV_EXPORT hio_t* hsendto (hloop_t* loop, int sockfd, const void* buf, size_t len, hwrite_cb write_cb DEFAULT(NULL)); + +//-----------------top-level apis--------------------------------------------- +// @hio_create_socket: socket -> bind -> listen +// sockaddr_set_ipport -> socket -> hio_get(loop, sockfd) -> +// side == HIO_SERVER_SIDE ? bind -> +// type & HIO_TYPE_SOCK_STREAM ? listen -> +HV_EXPORT hio_t* hio_create_socket(hloop_t* loop, const char* host, int port, + hio_type_e type DEFAULT(HIO_TYPE_TCP), + hio_side_e side DEFAULT(HIO_SERVER_SIDE)); + +// @tcp_server: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept +// @see examples/tcp_echo_server.c +HV_EXPORT hio_t* hloop_create_tcp_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); + +// @tcp_client: hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect +// @see examples/nc.c +HV_EXPORT hio_t* hloop_create_tcp_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); + +// @ssl_server: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_SERVER_SIDE) -> hio_setcb_accept -> hio_accept +// @see examples/tcp_echo_server.c => #define TEST_SSL 1 +HV_EXPORT hio_t* hloop_create_ssl_server (hloop_t* loop, const char* host, int port, haccept_cb accept_cb); + +// @ssl_client: hio_create_socket(loop, host, port, HIO_TYPE_SSL, HIO_CLIENT_SIDE) -> hio_setcb_connect -> hio_setcb_close -> hio_connect +// @see examples/nc.c => #define TEST_SSL 1 +HV_EXPORT hio_t* hloop_create_ssl_client (hloop_t* loop, const char* host, int port, hconnect_cb connect_cb, hclose_cb close_cb); + +// @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_SERVER_SIDE) +// @see examples/udp_echo_server.c +HV_EXPORT hio_t* hloop_create_udp_server (hloop_t* loop, const char* host, int port); + +// @udp_server: hio_create_socket(loop, host, port, HIO_TYPE_UDP, HIO_CLIENT_SIDE) +// @see examples/nc.c +HV_EXPORT hio_t* hloop_create_udp_client (hloop_t* loop, const char* host, int port); + +//-----------------upstream--------------------------------------------- +// hio_read(io) +// hio_read(io->upstream_io) +HV_EXPORT void hio_read_upstream(hio_t* io); +// on_write(io) -> hio_write_is_complete(io) -> hio_read(io->upstream_io) +HV_EXPORT void hio_read_upstream_on_write_complete(hio_t* io, const void* buf, int writebytes); +// hio_write(io->upstream_io, buf, bytes) +HV_EXPORT void hio_write_upstream(hio_t* io, void* buf, int bytes); +// hio_close(io->upstream_io) +HV_EXPORT void hio_close_upstream(hio_t* io); + +// io1->upstream_io = io2; +// io2->upstream_io = io1; +// @see examples/socks5_proxy_server.c +HV_EXPORT void hio_setup_upstream(hio_t* io1, hio_t* io2); + +// @return io->upstream_io +HV_EXPORT hio_t* hio_get_upstream(hio_t* io); + +// @tcp_upstream: hio_create_socket -> hio_setup_upstream -> hio_connect -> on_connect -> hio_read_upstream +// @return upstream_io +// @see examples/tcp_proxy_server.c +HV_EXPORT hio_t* hio_setup_tcp_upstream(hio_t* io, const char* host, int port, int ssl DEFAULT(0)); +#define hio_setup_ssl_upstream(io, host, port) hio_setup_tcp_upstream(io, host, port, 1) + +// @udp_upstream: hio_create_socket -> hio_setup_upstream -> hio_read_upstream +// @return upstream_io +// @see examples/udp_proxy_server.c +HV_EXPORT hio_t* hio_setup_udp_upstream(hio_t* io, const char* host, int port); + +//-----------------unpack--------------------------------------------- +typedef enum { + UNPACK_MODE_NONE = 0, + UNPACK_BY_FIXED_LENGTH = 1, // Not recommended + UNPACK_BY_DELIMITER = 2, // Suitable for text protocol + UNPACK_BY_LENGTH_FIELD = 3, // Suitable for binary protocol +} unpack_mode_e; + +#define DEFAULT_PACKAGE_MAX_LENGTH (1 << 21) // 2M + +// UNPACK_BY_DELIMITER +#define PACKAGE_MAX_DELIMITER_BYTES 8 + +// UNPACK_BY_LENGTH_FIELD +typedef enum { + ENCODE_BY_VARINT = 17, // 1 MSB + 7 bits + ENCODE_BY_LITTEL_ENDIAN = LITTLE_ENDIAN, // 1234 + ENCODE_BY_BIG_ENDIAN = BIG_ENDIAN, // 4321 +} unpack_coding_e; + +typedef struct unpack_setting_s { + unpack_mode_e mode; + unsigned int package_max_length; + union { + // UNPACK_BY_FIXED_LENGTH + struct { + unsigned int fixed_length; + }; + // UNPACK_BY_DELIMITER + struct { + unsigned char delimiter[PACKAGE_MAX_DELIMITER_BYTES]; + unsigned short delimiter_bytes; + }; + /* + * UNPACK_BY_LENGTH_FIELD + * + * package_len = head_len + body_len + length_adjustment + * + * if (length_field_coding == ENCODE_BY_VARINT) head_len = body_offset + varint_bytes - length_field_bytes; + * else head_len = body_offset; + * + * length_field stores body length, exclude head length, + * if length_field = head_len + body_len, then length_adjustment should be set to -head_len. + * + */ + struct { + unsigned short body_offset; // Equal to head length usually + unsigned short length_field_offset; + unsigned short length_field_bytes; + short length_adjustment; + unpack_coding_e length_field_coding; + }; + }; +#ifdef __cplusplus + unpack_setting_s() { + // Recommended setting: + // head = flags:1byte + length:4bytes = 5bytes + mode = UNPACK_BY_LENGTH_FIELD; + package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + fixed_length = 0; + delimiter_bytes = 0; + body_offset = 5; + length_field_offset = 1; + length_field_bytes = 4; + length_field_coding = ENCODE_BY_BIG_ENDIAN; + length_adjustment = 0; + } +#endif +} unpack_setting_t; + +/* + * @see examples/jsonrpc examples/protorpc + * + * NOTE: unpack_setting_t of multiple IOs of the same function also are same, + * so only the pointer of unpack_setting_t is stored in hio_t, + * the life time of unpack_setting_t shoud be guaranteed by caller. + */ +HV_EXPORT void hio_set_unpack(hio_t* io, unpack_setting_t* setting); +HV_EXPORT void hio_unset_unpack(hio_t* io); + +// unpack examples +/* +unpack_setting_t ftp_unpack_setting; +memset(&ftp_unpack_setting, 0, sizeof(unpack_setting_t)); +ftp_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; +ftp_unpack_setting.mode = UNPACK_BY_DELIMITER; +ftp_unpack_setting.delimiter[0] = '\r'; +ftp_unpack_setting.delimiter[1] = '\n'; +ftp_unpack_setting.delimiter_bytes = 2; + +unpack_setting_t mqtt_unpack_setting = { + .mode = UNPACK_BY_LENGTH_FIELD, + .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, + .body_offset = 2, + .length_field_offset = 1, + .length_field_bytes = 1, + .length_field_coding = ENCODE_BY_VARINT, +}; + +unpack_setting_t grpc_unpack_setting = { + .mode = UNPACK_BY_LENGTH_FIELD, + .package_max_length = DEFAULT_PACKAGE_MAX_LENGTH, + .body_offset = 5, + .length_field_offset = 1, + .length_field_bytes = 4, + .length_field_coding = ENCODE_BY_BIG_ENDIAN, +}; +*/ + +//-----------------reconnect---------------------------------------- +#define DEFAULT_RECONNECT_MIN_DELAY 1000 // ms +#define DEFAULT_RECONNECT_MAX_DELAY 60000 // ms +#define DEFAULT_RECONNECT_DELAY_POLICY 2 // exponential +#define DEFAULT_RECONNECT_MAX_RETRY_CNT INFINITE +typedef struct reconn_setting_s { + uint32_t min_delay; // ms + uint32_t max_delay; // ms + uint32_t cur_delay; // ms + /* + * @delay_policy + * 0: fixed + * min_delay=3s => 3,3,3... + * 1: linear + * min_delay=3s max_delay=10s => 3,6,9,10,10... + * other: exponential + * min_delay=3s max_delay=60s delay_policy=2 => 3,6,12,24,48,60,60... + */ + uint32_t delay_policy; + uint32_t max_retry_cnt; + uint32_t cur_retry_cnt; + +#ifdef __cplusplus + reconn_setting_s() { + min_delay = DEFAULT_RECONNECT_MIN_DELAY; + max_delay = DEFAULT_RECONNECT_MAX_DELAY; + cur_delay = 0; + // 1,2,4,8,16,32,60,60... + delay_policy = DEFAULT_RECONNECT_DELAY_POLICY; + max_retry_cnt = DEFAULT_RECONNECT_MAX_RETRY_CNT; + cur_retry_cnt = 0; + } +#endif +} reconn_setting_t; + +HV_INLINE void reconn_setting_init(reconn_setting_t* reconn) { + reconn->min_delay = DEFAULT_RECONNECT_MIN_DELAY; + reconn->max_delay = DEFAULT_RECONNECT_MAX_DELAY; + reconn->cur_delay = 0; + // 1,2,4,8,16,32,60,60... + reconn->delay_policy = DEFAULT_RECONNECT_DELAY_POLICY; + reconn->max_retry_cnt = DEFAULT_RECONNECT_MAX_RETRY_CNT; + reconn->cur_retry_cnt = 0; +} + +HV_INLINE void reconn_setting_reset(reconn_setting_t* reconn) { + reconn->cur_delay = 0; + reconn->cur_retry_cnt = 0; +} + +HV_INLINE bool reconn_setting_can_retry(reconn_setting_t* reconn) { + ++reconn->cur_retry_cnt; + return reconn->max_retry_cnt == INFINITE || + reconn->cur_retry_cnt < reconn->max_retry_cnt; +} + +HV_INLINE uint32_t reconn_setting_calc_delay(reconn_setting_t* reconn) { + if (reconn->delay_policy == 0) { + // fixed + reconn->cur_delay = reconn->min_delay; + } else if (reconn->delay_policy == 1) { + // linear + reconn->cur_delay += reconn->min_delay; + } else { + // exponential + reconn->cur_delay *= reconn->delay_policy; + } + reconn->cur_delay = MAX(reconn->cur_delay, reconn->min_delay); + reconn->cur_delay = MIN(reconn->cur_delay, reconn->max_delay); + return reconn->cur_delay; +} + +//-----------------LoadBalance------------------------------------- +typedef enum { + LB_RoundRobin, + LB_Random, + LB_LeastConnections, + LB_IpHash, + LB_UrlHash, +} load_balance_e; + +//-----------------rudp--------------------------------------------- +#if WITH_KCP +#define WITH_RUDP 1 +#endif + +#if WITH_RUDP +// NOTE: hio_close_rudp is thread-safe. +HV_EXPORT int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr DEFAULT(NULL)); +#endif + +#if WITH_KCP +typedef struct kcp_setting_s { + // ikcp_create(conv, ...) + unsigned int conv; + // ikcp_nodelay(kcp, nodelay, interval, fastresend, nocwnd) + int nodelay; + int interval; + int fastresend; + int nocwnd; + // ikcp_wndsize(kcp, sndwnd, rcvwnd) + int sndwnd; + int rcvwnd; + // ikcp_setmtu(kcp, mtu) + int mtu; + // ikcp_update + int update_interval; + +#ifdef __cplusplus + kcp_setting_s() { + conv = 0x11223344; + // normal mode + nodelay = 0; + interval = 40; + fastresend = 0; + nocwnd = 0; + // fast mode + // nodelay = 1; + // interval = 10; + // fastresend = 2; + // nocwnd = 1; + + sndwnd = 0; + rcvwnd = 0; + mtu = 1400; + update_interval = 10; // ms + } +#endif +} kcp_setting_t; + +HV_INLINE void kcp_setting_init_with_normal_mode(kcp_setting_t* setting) { + memset(setting, 0, sizeof(kcp_setting_t)); + setting->nodelay = 0; + setting->interval = 40; + setting->fastresend = 0; + setting->nocwnd = 0; +} + +HV_INLINE void kcp_setting_init_with_fast_mode(kcp_setting_t* setting) { + memset(setting, 0, sizeof(kcp_setting_t)); + setting->nodelay = 0; + setting->interval = 30; + setting->fastresend = 2; + setting->nocwnd = 1; +} + +HV_INLINE void kcp_setting_init_with_fast2_mode(kcp_setting_t* setting) { + memset(setting, 0, sizeof(kcp_setting_t)); + setting->nodelay = 1; + setting->interval = 20; + setting->fastresend = 2; + setting->nocwnd = 1; +} + +HV_INLINE void kcp_setting_init_with_fast3_mode(kcp_setting_t* setting) { + memset(setting, 0, sizeof(kcp_setting_t)); + setting->nodelay = 1; + setting->interval = 10; + setting->fastresend = 2; + setting->nocwnd = 1; +} + +// @see examples/udp_echo_server.c => #define TEST_KCP 1 +HV_EXPORT int hio_set_kcp(hio_t* io, kcp_setting_t* setting DEFAULT(NULL)); +#endif + +END_EXTERN_C + +#endif // HV_LOOP_H_ diff --git a/external/libhv/libhv-1.3.2/event/iocp.c b/external/libhv/libhv-1.3.2/event/iocp.c new file mode 100644 index 0000000..caef1cf --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/iocp.c @@ -0,0 +1,81 @@ +#include "iowatcher.h" + +#ifdef EVENT_IOCP +#include "hplatform.h" +#include "hdef.h" + +#include "hevent.h" +#include "overlapio.h" + +typedef struct iocp_ctx_s { + HANDLE iocp; +} iocp_ctx_t; + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + iocp_ctx_t* iocp_ctx; + HV_ALLOC_SIZEOF(iocp_ctx); + iocp_ctx->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); + loop->iowatcher = iocp_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + if (loop->iowatcher == NULL) return 0; + iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; + CloseHandle(iocp_ctx->iocp); + HV_FREE(loop->iowatcher); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; + hio_t* io = loop->ios.ptr[fd]; + if (io && io->events == 0 && events != 0) { + CreateIoCompletionPort((HANDLE)fd, iocp_ctx->iocp, 0, 0); + } + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + hio_t* io = loop->ios.ptr[fd]; + if ((io->events & ~events) == 0) { + CancelIo((HANDLE)fd); + } + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + if (loop->iowatcher == NULL) return 0; + iocp_ctx_t* iocp_ctx = (iocp_ctx_t*)loop->iowatcher; + DWORD bytes = 0; + ULONG_PTR key = 0; + LPOVERLAPPED povlp = NULL; + BOOL bRet = GetQueuedCompletionStatus(iocp_ctx->iocp, &bytes, &key, &povlp, timeout); + int err = 0; + if (povlp == NULL) { + err = WSAGetLastError(); + if (err == WAIT_TIMEOUT || ERROR_NETNAME_DELETED || ERROR_OPERATION_ABORTED) { + return 0; + } + return -err; + } + hoverlapped_t* hovlp = (hoverlapped_t*)povlp; + hio_t* io = hovlp->io; + if (bRet == FALSE) { + err = WSAGetLastError(); + printd("iocp ret=%d err=%d bytes=%u\n", bRet, err, bytes); + // NOTE: when ConnectEx failed, err != 0 + hovlp->error = err; + } + // NOTE: when WSASend/WSARecv disconnect, bytes = 0 + hovlp->bytes = bytes; + io->hovlp = hovlp; + io->revents |= hovlp->event; + EVENT_PENDING(hovlp->io); + return 1; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/iowatcher.h b/external/libhv/libhv-1.3.2/event/iowatcher.h new file mode 100644 index 0000000..1c6853d --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/iowatcher.h @@ -0,0 +1,39 @@ +#ifndef IO_WATCHER_H_ +#define IO_WATCHER_H_ + +#include "hloop.h" + +#include "hplatform.h" +#if !defined(EVENT_SELECT) && \ + !defined(EVENT_POLL) && \ + !defined(EVENT_EPOLL) && \ + !defined(EVENT_KQUEUE) && \ + !defined(EVENT_IOCP) && \ + !defined(EVENT_PORT) && \ + !defined(EVENT_NOEVENT) +#ifdef OS_WIN + #if WITH_WEPOLL + #define EVENT_EPOLL // wepoll -> iocp + #else + #define EVENT_POLL // WSAPoll + #endif +#elif defined(OS_LINUX) +#define EVENT_EPOLL +#elif defined(OS_MAC) +#define EVENT_KQUEUE +#elif defined(OS_BSD) +#define EVENT_KQUEUE +#elif defined(OS_SOLARIS) +#define EVENT_PORT +#else +#define EVENT_SELECT +#endif +#endif + +int iowatcher_init(hloop_t* loop); +int iowatcher_cleanup(hloop_t* loop); +int iowatcher_add_event(hloop_t* loop, int fd, int events); +int iowatcher_del_event(hloop_t* loop, int fd, int events); +int iowatcher_poll_events(hloop_t* loop, int timeout); + +#endif diff --git a/external/libhv/libhv-1.3.2/event/kcp/LICENSE b/external/libhv/libhv-1.3.2/event/kcp/LICENSE new file mode 100644 index 0000000..4f9f28f --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kcp/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Lin Wei (skywind3000 at gmail.com) + +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. \ No newline at end of file diff --git a/external/libhv/libhv-1.3.2/event/kcp/hkcp.c b/external/libhv/libhv-1.3.2/event/kcp/hkcp.c new file mode 100644 index 0000000..2c9fe6c --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kcp/hkcp.c @@ -0,0 +1,150 @@ +#include "hkcp.h" + +#if WITH_KCP + +#include "hevent.h" +#include "hlog.h" +#include "hthread.h" + +static kcp_setting_t s_kcp_setting; + +static int __kcp_output(const char* buf, int len, ikcpcb* ikcp, void* userdata) { + // printf("ikcp_output len=%d\n", len); + rudp_entry_t* rudp = (rudp_entry_t*)userdata; + assert(rudp != NULL && rudp->io != NULL); + int nsend = sendto(rudp->io->fd, buf, len, 0, &rudp->addr.sa, SOCKADDR_LEN(&rudp->addr)); + // printf("sendto nsend=%d\n", nsend); + return nsend; +} + +static void __kcp_update_timer_cb(htimer_t* timer) { + rudp_entry_t* rudp = (rudp_entry_t*)timer->privdata; + assert(rudp != NULL && rudp->io != NULL && rudp->kcp.ikcp != NULL); + ikcp_update(rudp->kcp.ikcp, (IUINT32)(rudp->io->loop->cur_hrtime / 1000)); +} + +void kcp_release(kcp_t* kcp) { + if (kcp->ikcp == NULL) return; + if (kcp->update_timer) { + htimer_del(kcp->update_timer); + kcp->update_timer = NULL; + } + HV_FREE(kcp->readbuf.base); + kcp->readbuf.len = 0; + // printf("ikcp_release ikcp=%p\n", kcp->ikcp); + ikcp_release(kcp->ikcp); + kcp->ikcp = NULL; +} + +int hio_set_kcp(hio_t* io, kcp_setting_t* setting) { + io->io_type = HIO_TYPE_KCP; + io->kcp_setting = setting; + return 0; +} + +kcp_t* hio_get_kcp(hio_t* io, uint32_t conv) { + rudp_entry_t* rudp = hio_get_rudp(io); + assert(rudp != NULL); + kcp_t* kcp = &rudp->kcp; + if (kcp->ikcp != NULL) return kcp; + if (io->kcp_setting == NULL) { + io->kcp_setting = &s_kcp_setting; + } + kcp_setting_t* setting = io->kcp_setting; + kcp->ikcp = ikcp_create(conv, rudp); + // printf("ikcp_create conv=%u ikcp=%p\n", conv, kcp->ikcp); + kcp->ikcp->output = __kcp_output; + kcp->conv = conv; + if (setting->interval > 0) { + ikcp_nodelay(kcp->ikcp, setting->nodelay, setting->interval, setting->fastresend, setting->nocwnd); + } + if (setting->sndwnd > 0 && setting->rcvwnd > 0) { + ikcp_wndsize(kcp->ikcp, setting->sndwnd, setting->rcvwnd); + } + if (setting->mtu > 0) { + ikcp_setmtu(kcp->ikcp, setting->mtu); + } + if (kcp->update_timer == NULL) { + int update_interval = setting->update_interval; + if (update_interval == 0) { + update_interval = DEFAULT_KCP_UPDATE_INTERVAL; + } + kcp->update_timer = htimer_add(io->loop, __kcp_update_timer_cb, update_interval, INFINITE); + kcp->update_timer->privdata = rudp; + } + // NOTE: alloc kcp->readbuf when hio_read_kcp + return kcp; +} + +static void hio_write_kcp_event_cb(hevent_t* ev) { + hio_t* io = (hio_t*)ev->userdata; + hbuf_t* buf = (hbuf_t*)ev->privdata; + + hio_write_kcp(io, buf->base, buf->len); + + HV_FREE(buf); +} + +static int hio_write_kcp_async(hio_t* io, const void* data, size_t len) { + hbuf_t* buf = NULL; + HV_ALLOC(buf, sizeof(hbuf_t) + len); + buf->base = (char*)buf + sizeof(hbuf_t); + buf->len = len; + memcpy(buf->base, data, len); + + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.cb = hio_write_kcp_event_cb; + ev.userdata = io; + ev.privdata = buf; + hloop_post_event(io->loop, &ev); + return len; +} + +int hio_write_kcp(hio_t* io, const void* buf, size_t len) { + if (hv_gettid() != io->loop->tid) { + return hio_write_kcp_async(io, buf, len); + } + IUINT32 conv = io->kcp_setting ? io->kcp_setting->conv : 0; + kcp_t* kcp = hio_get_kcp(io, conv); + // printf("hio_write_kcp conv=%u=%u\n", conv, kcp->conv); + int nsend = ikcp_send(kcp->ikcp, (const char*)buf, len); + // printf("ikcp_send len=%d nsend=%d\n", (int)len, nsend); + if (nsend < 0) { + hloge("ikcp_send error: %d", nsend); + return nsend; + } + ikcp_update(kcp->ikcp, (IUINT32)io->loop->cur_hrtime / 1000); + return len; +} + +int hio_read_kcp (hio_t* io, void* buf, int readbytes) { + IUINT32 conv = ikcp_getconv(buf); + kcp_t* kcp = hio_get_kcp(io, conv); + // printf("hio_read_kcp conv=%u=%u\n", conv, kcp->conv); + if (kcp->conv != conv) { + hloge("recv invalid kcp packet!"); + hio_close_rudp(io, io->peeraddr); + return -1; + } + // printf("ikcp_input len=%d\n", readbytes); + int ret = ikcp_input(kcp->ikcp, (const char*)buf, readbytes); + // printf("ikcp_input ret=%d\n", ret); + if (ret != 0) { + return 0; + } + if (kcp->readbuf.base == NULL || kcp->readbuf.len == 0) { + kcp->readbuf.len = DEFAULT_KCP_READ_BUFSIZE; + HV_ALLOC(kcp->readbuf.base, kcp->readbuf.len); + } + while (1) { + int nrecv = ikcp_recv(kcp->ikcp, kcp->readbuf.base, kcp->readbuf.len); + // printf("ikcp_recv nrecv=%d\n", nrecv); + if (nrecv < 0) break; + hio_read_cb(io, kcp->readbuf.base, nrecv); + ret += nrecv; + } + return ret; +} + +#endif diff --git a/external/libhv/libhv-1.3.2/event/kcp/hkcp.h b/external/libhv/libhv-1.3.2/event/kcp/hkcp.h new file mode 100644 index 0000000..ca9a061 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kcp/hkcp.h @@ -0,0 +1,30 @@ +#ifndef HV_KCP_H_ +#define HV_KCP_H_ + +#include "hloop.h" + +#if WITH_KCP + +#include "ikcp.h" +#include "hbuf.h" + +#define DEFAULT_KCP_UPDATE_INTERVAL 10 // ms +#define DEFAULT_KCP_READ_BUFSIZE 1400 + +typedef struct kcp_s { + ikcpcb* ikcp; + uint32_t conv; + htimer_t* update_timer; + hbuf_t readbuf; +} kcp_t; + +// NOTE: kcp_create in hio_get_kcp +void kcp_release(kcp_t* kcp); + +kcp_t* hio_get_kcp (hio_t* io, uint32_t conv); +int hio_read_kcp (hio_t* io, void* buf, int readbytes); +int hio_write_kcp(hio_t* io, const void* buf, size_t len); + +#endif + +#endif // HV_KCP_H_ diff --git a/external/libhv/libhv-1.3.2/event/kcp/ikcp.c b/external/libhv/libhv-1.3.2/event/kcp/ikcp.c new file mode 100644 index 0000000..fd4cf7d --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kcp/ikcp.c @@ -0,0 +1,1299 @@ +//===================================================================== +// +// KCP - A Better ARQ Protocol Implementation +// skywind3000 (at) gmail.com, 2010-2011 +// +// Features: +// + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. +// + Maximum RTT reduce three times vs tcp. +// + Lightweight, distributed as a single source file. +// +//===================================================================== +#include "ikcp.h" + +#include +#include +#include +#include +#include + + + +//===================================================================== +// KCP BASIC +//===================================================================== +const IUINT32 IKCP_RTO_NDL = 30; // no delay min rto +const IUINT32 IKCP_RTO_MIN = 100; // normal min rto +const IUINT32 IKCP_RTO_DEF = 200; +const IUINT32 IKCP_RTO_MAX = 60000; +const IUINT32 IKCP_CMD_PUSH = 81; // cmd: push data +const IUINT32 IKCP_CMD_ACK = 82; // cmd: ack +const IUINT32 IKCP_CMD_WASK = 83; // cmd: window probe (ask) +const IUINT32 IKCP_CMD_WINS = 84; // cmd: window size (tell) +const IUINT32 IKCP_ASK_SEND = 1; // need to send IKCP_CMD_WASK +const IUINT32 IKCP_ASK_TELL = 2; // need to send IKCP_CMD_WINS +const IUINT32 IKCP_WND_SND = 32; +const IUINT32 IKCP_WND_RCV = 128; // must >= max fragment size +const IUINT32 IKCP_MTU_DEF = 1400; +const IUINT32 IKCP_ACK_FAST = 3; +const IUINT32 IKCP_INTERVAL = 100; +const IUINT32 IKCP_OVERHEAD = 24; +const IUINT32 IKCP_DEADLINK = 20; +const IUINT32 IKCP_THRESH_INIT = 2; +const IUINT32 IKCP_THRESH_MIN = 2; +const IUINT32 IKCP_PROBE_INIT = 7000; // 7 secs to probe window size +const IUINT32 IKCP_PROBE_LIMIT = 120000; // up to 120 secs to probe window +const IUINT32 IKCP_FASTACK_LIMIT = 5; // max times to trigger fastack + + +//--------------------------------------------------------------------- +// encode / decode +//--------------------------------------------------------------------- + +/* encode 8 bits unsigned int */ +static inline char *ikcp_encode8u(char *p, unsigned char c) +{ + *(unsigned char*)p++ = c; + return p; +} + +/* decode 8 bits unsigned int */ +static inline const char *ikcp_decode8u(const char *p, unsigned char *c) +{ + *c = *(unsigned char*)p++; + return p; +} + +/* encode 16 bits unsigned int (lsb) */ +static inline char *ikcp_encode16u(char *p, unsigned short w) +{ +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *(unsigned char*)(p + 0) = (w & 255); + *(unsigned char*)(p + 1) = (w >> 8); +#else + memcpy(p, &w, 2); +#endif + p += 2; + return p; +} + +/* decode 16 bits unsigned int (lsb) */ +static inline const char *ikcp_decode16u(const char *p, unsigned short *w) +{ +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *w = *(const unsigned char*)(p + 1); + *w = *(const unsigned char*)(p + 0) + (*w << 8); +#else + memcpy(w, p, 2); +#endif + p += 2; + return p; +} + +/* encode 32 bits unsigned int (lsb) */ +static inline char *ikcp_encode32u(char *p, IUINT32 l) +{ +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *(unsigned char*)(p + 0) = (unsigned char)((l >> 0) & 0xff); + *(unsigned char*)(p + 1) = (unsigned char)((l >> 8) & 0xff); + *(unsigned char*)(p + 2) = (unsigned char)((l >> 16) & 0xff); + *(unsigned char*)(p + 3) = (unsigned char)((l >> 24) & 0xff); +#else + memcpy(p, &l, 4); +#endif + p += 4; + return p; +} + +/* decode 32 bits unsigned int (lsb) */ +static inline const char *ikcp_decode32u(const char *p, IUINT32 *l) +{ +#if IWORDS_BIG_ENDIAN || IWORDS_MUST_ALIGN + *l = *(const unsigned char*)(p + 3); + *l = *(const unsigned char*)(p + 2) + (*l << 8); + *l = *(const unsigned char*)(p + 1) + (*l << 8); + *l = *(const unsigned char*)(p + 0) + (*l << 8); +#else + memcpy(l, p, 4); +#endif + p += 4; + return p; +} + +static inline IUINT32 _imin_(IUINT32 a, IUINT32 b) { + return a <= b ? a : b; +} + +static inline IUINT32 _imax_(IUINT32 a, IUINT32 b) { + return a >= b ? a : b; +} + +static inline IUINT32 _ibound_(IUINT32 lower, IUINT32 middle, IUINT32 upper) +{ + return _imin_(_imax_(lower, middle), upper); +} + +static inline long _itimediff(IUINT32 later, IUINT32 earlier) +{ + return ((IINT32)(later - earlier)); +} + +//--------------------------------------------------------------------- +// manage segment +//--------------------------------------------------------------------- +typedef struct IKCPSEG IKCPSEG; + +static void* (*ikcp_malloc_hook)(size_t) = NULL; +static void (*ikcp_free_hook)(void *) = NULL; + +// internal malloc +static void* ikcp_malloc(size_t size) { + if (ikcp_malloc_hook) + return ikcp_malloc_hook(size); + return malloc(size); +} + +// internal free +static void ikcp_free(void *ptr) { + if (ikcp_free_hook) { + ikcp_free_hook(ptr); + } else { + free(ptr); + } +} + +// redefine allocator +void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)) +{ + ikcp_malloc_hook = new_malloc; + ikcp_free_hook = new_free; +} + +// allocate a new kcp segment +static IKCPSEG* ikcp_segment_new(ikcpcb *kcp, int size) +{ + return (IKCPSEG*)ikcp_malloc(sizeof(IKCPSEG) + size); +} + +// delete a segment +static void ikcp_segment_delete(ikcpcb *kcp, IKCPSEG *seg) +{ + ikcp_free(seg); +} + +// write log +void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...) +{ + char buffer[1024]; + va_list argptr; + if ((mask & kcp->logmask) == 0 || kcp->writelog == 0) return; + va_start(argptr, fmt); + vsprintf(buffer, fmt, argptr); + va_end(argptr); + kcp->writelog(buffer, kcp, kcp->user); +} + +// check log mask +static int ikcp_canlog(const ikcpcb *kcp, int mask) +{ + if ((mask & kcp->logmask) == 0 || kcp->writelog == NULL) return 0; + return 1; +} + +// output segment +static int ikcp_output(ikcpcb *kcp, const void *data, int size) +{ + assert(kcp); + assert(kcp->output); + if (ikcp_canlog(kcp, IKCP_LOG_OUTPUT)) { + ikcp_log(kcp, IKCP_LOG_OUTPUT, "[RO] %ld bytes", (long)size); + } + if (size == 0) return 0; + return kcp->output((const char*)data, size, kcp, kcp->user); +} + +// output queue +void ikcp_qprint(const char *name, const struct IQUEUEHEAD *head) +{ +#if 0 + const struct IQUEUEHEAD *p; + printf("<%s>: [", name); + for (p = head->next; p != head; p = p->next) { + const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); + printf("(%lu %d)", (unsigned long)seg->sn, (int)(seg->ts % 10000)); + if (p->next != head) printf(","); + } + printf("]\n"); +#endif +} + + +//--------------------------------------------------------------------- +// create a new kcpcb +//--------------------------------------------------------------------- +ikcpcb* ikcp_create(IUINT32 conv, void *user) +{ + ikcpcb *kcp = (ikcpcb*)ikcp_malloc(sizeof(struct IKCPCB)); + if (kcp == NULL) return NULL; + kcp->conv = conv; + kcp->user = user; + kcp->snd_una = 0; + kcp->snd_nxt = 0; + kcp->rcv_nxt = 0; + kcp->ts_recent = 0; + kcp->ts_lastack = 0; + kcp->ts_probe = 0; + kcp->probe_wait = 0; + kcp->snd_wnd = IKCP_WND_SND; + kcp->rcv_wnd = IKCP_WND_RCV; + kcp->rmt_wnd = IKCP_WND_RCV; + kcp->cwnd = 0; + kcp->incr = 0; + kcp->probe = 0; + kcp->mtu = IKCP_MTU_DEF; + kcp->mss = kcp->mtu - IKCP_OVERHEAD; + kcp->stream = 0; + + kcp->buffer = (char*)ikcp_malloc((kcp->mtu + IKCP_OVERHEAD) * 3); + if (kcp->buffer == NULL) { + ikcp_free(kcp); + return NULL; + } + + iqueue_init(&kcp->snd_queue); + iqueue_init(&kcp->rcv_queue); + iqueue_init(&kcp->snd_buf); + iqueue_init(&kcp->rcv_buf); + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->state = 0; + kcp->acklist = NULL; + kcp->ackblock = 0; + kcp->ackcount = 0; + kcp->rx_srtt = 0; + kcp->rx_rttval = 0; + kcp->rx_rto = IKCP_RTO_DEF; + kcp->rx_minrto = IKCP_RTO_MIN; + kcp->current = 0; + kcp->interval = IKCP_INTERVAL; + kcp->ts_flush = IKCP_INTERVAL; + kcp->nodelay = 0; + kcp->updated = 0; + kcp->logmask = 0; + kcp->ssthresh = IKCP_THRESH_INIT; + kcp->fastresend = 0; + kcp->fastlimit = IKCP_FASTACK_LIMIT; + kcp->nocwnd = 0; + kcp->xmit = 0; + kcp->dead_link = IKCP_DEADLINK; + kcp->output = NULL; + kcp->writelog = NULL; + + return kcp; +} + + +//--------------------------------------------------------------------- +// release a new kcpcb +//--------------------------------------------------------------------- +void ikcp_release(ikcpcb *kcp) +{ + assert(kcp); + if (kcp) { + IKCPSEG *seg; + while (!iqueue_is_empty(&kcp->snd_buf)) { + seg = iqueue_entry(kcp->snd_buf.next, IKCPSEG, node); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + while (!iqueue_is_empty(&kcp->rcv_buf)) { + seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + while (!iqueue_is_empty(&kcp->snd_queue)) { + seg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + while (!iqueue_is_empty(&kcp->rcv_queue)) { + seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + } + if (kcp->buffer) { + ikcp_free(kcp->buffer); + } + if (kcp->acklist) { + ikcp_free(kcp->acklist); + } + + kcp->nrcv_buf = 0; + kcp->nsnd_buf = 0; + kcp->nrcv_que = 0; + kcp->nsnd_que = 0; + kcp->ackcount = 0; + kcp->buffer = NULL; + kcp->acklist = NULL; + ikcp_free(kcp); + } +} + + +//--------------------------------------------------------------------- +// set output callback, which will be invoked by kcp +//--------------------------------------------------------------------- +void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, + ikcpcb *kcp, void *user)) +{ + kcp->output = output; +} + + +//--------------------------------------------------------------------- +// user/upper level recv: returns size, returns below zero for EAGAIN +//--------------------------------------------------------------------- +int ikcp_recv(ikcpcb *kcp, char *buffer, int len) +{ + struct IQUEUEHEAD *p; + int ispeek = (len < 0)? 1 : 0; + int peeksize; + int recover = 0; + IKCPSEG *seg; + assert(kcp); + + if (iqueue_is_empty(&kcp->rcv_queue)) + return -1; + + if (len < 0) len = -len; + + peeksize = ikcp_peeksize(kcp); + + if (peeksize < 0) + return -2; + + if (peeksize > len) + return -3; + + if (kcp->nrcv_que >= kcp->rcv_wnd) + recover = 1; + + // merge fragment + for (len = 0, p = kcp->rcv_queue.next; p != &kcp->rcv_queue; ) { + int fragment; + seg = iqueue_entry(p, IKCPSEG, node); + p = p->next; + + if (buffer) { + memcpy(buffer, seg->data, seg->len); + buffer += seg->len; + } + + len += seg->len; + fragment = seg->frg; + + if (ikcp_canlog(kcp, IKCP_LOG_RECV)) { + ikcp_log(kcp, IKCP_LOG_RECV, "recv sn=%lu", (unsigned long)seg->sn); + } + + if (ispeek == 0) { + iqueue_del(&seg->node); + ikcp_segment_delete(kcp, seg); + kcp->nrcv_que--; + } + + if (fragment == 0) + break; + } + + assert(len == peeksize); + + // move available data from rcv_buf -> rcv_queue + while (! iqueue_is_empty(&kcp->rcv_buf)) { + seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } else { + break; + } + } + + // fast recover + if (kcp->nrcv_que < kcp->rcv_wnd && recover) { + // ready to send back IKCP_CMD_WINS in ikcp_flush + // tell remote my window size + kcp->probe |= IKCP_ASK_TELL; + } + + return len; +} + + +//--------------------------------------------------------------------- +// peek data size +//--------------------------------------------------------------------- +int ikcp_peeksize(const ikcpcb *kcp) +{ + struct IQUEUEHEAD *p; + IKCPSEG *seg; + int length = 0; + + assert(kcp); + + if (iqueue_is_empty(&kcp->rcv_queue)) return -1; + + seg = iqueue_entry(kcp->rcv_queue.next, IKCPSEG, node); + if (seg->frg == 0) return seg->len; + + if (kcp->nrcv_que < seg->frg + 1) return -1; + + for (p = kcp->rcv_queue.next; p != &kcp->rcv_queue; p = p->next) { + seg = iqueue_entry(p, IKCPSEG, node); + length += seg->len; + if (seg->frg == 0) break; + } + + return length; +} + + +//--------------------------------------------------------------------- +// user/upper level send, returns below zero for error +//--------------------------------------------------------------------- +int ikcp_send(ikcpcb *kcp, const char *buffer, int len) +{ + IKCPSEG *seg; + int count, i; + + assert(kcp->mss > 0); + if (len < 0) return -1; + + // append to previous segment in streaming mode (if possible) + if (kcp->stream != 0) { + if (!iqueue_is_empty(&kcp->snd_queue)) { + IKCPSEG *old = iqueue_entry(kcp->snd_queue.prev, IKCPSEG, node); + if (old->len < kcp->mss) { + int capacity = kcp->mss - old->len; + int extend = (len < capacity)? len : capacity; + seg = ikcp_segment_new(kcp, old->len + extend); + assert(seg); + if (seg == NULL) { + return -2; + } + iqueue_add_tail(&seg->node, &kcp->snd_queue); + memcpy(seg->data, old->data, old->len); + if (buffer) { + memcpy(seg->data + old->len, buffer, extend); + buffer += extend; + } + seg->len = old->len + extend; + seg->frg = 0; + len -= extend; + iqueue_del_init(&old->node); + ikcp_segment_delete(kcp, old); + } + } + if (len <= 0) { + return 0; + } + } + + if (len <= (int)kcp->mss) count = 1; + else count = (len + kcp->mss - 1) / kcp->mss; + + if (count >= (int)IKCP_WND_RCV) return -2; + + if (count == 0) count = 1; + + // fragment + for (i = 0; i < count; i++) { + int size = len > (int)kcp->mss ? (int)kcp->mss : len; + seg = ikcp_segment_new(kcp, size); + assert(seg); + if (seg == NULL) { + return -2; + } + if (buffer && len > 0) { + memcpy(seg->data, buffer, size); + } + seg->len = size; + seg->frg = (kcp->stream == 0)? (count - i - 1) : 0; + iqueue_init(&seg->node); + iqueue_add_tail(&seg->node, &kcp->snd_queue); + kcp->nsnd_que++; + if (buffer) { + buffer += size; + } + len -= size; + } + + return 0; +} + + +//--------------------------------------------------------------------- +// parse ack +//--------------------------------------------------------------------- +static void ikcp_update_ack(ikcpcb *kcp, IINT32 rtt) +{ + IINT32 rto = 0; + if (kcp->rx_srtt == 0) { + kcp->rx_srtt = rtt; + kcp->rx_rttval = rtt / 2; + } else { + long delta = rtt - kcp->rx_srtt; + if (delta < 0) delta = -delta; + kcp->rx_rttval = (3 * kcp->rx_rttval + delta) / 4; + kcp->rx_srtt = (7 * kcp->rx_srtt + rtt) / 8; + if (kcp->rx_srtt < 1) kcp->rx_srtt = 1; + } + rto = kcp->rx_srtt + _imax_(kcp->interval, 4 * kcp->rx_rttval); + kcp->rx_rto = _ibound_(kcp->rx_minrto, rto, IKCP_RTO_MAX); +} + +static void ikcp_shrink_buf(ikcpcb *kcp) +{ + struct IQUEUEHEAD *p = kcp->snd_buf.next; + if (p != &kcp->snd_buf) { + IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); + kcp->snd_una = seg->sn; + } else { + kcp->snd_una = kcp->snd_nxt; + } +} + +static void ikcp_parse_ack(ikcpcb *kcp, IUINT32 sn) +{ + struct IQUEUEHEAD *p, *next; + + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { + IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); + next = p->next; + if (sn == seg->sn) { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + break; + } + if (_itimediff(sn, seg->sn) < 0) { + break; + } + } +} + +static void ikcp_parse_una(ikcpcb *kcp, IUINT32 una) +{ + struct IQUEUEHEAD *p, *next; + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { + IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); + next = p->next; + if (_itimediff(una, seg->sn) > 0) { + iqueue_del(p); + ikcp_segment_delete(kcp, seg); + kcp->nsnd_buf--; + } else { + break; + } + } +} + +static void ikcp_parse_fastack(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) +{ + struct IQUEUEHEAD *p, *next; + + if (_itimediff(sn, kcp->snd_una) < 0 || _itimediff(sn, kcp->snd_nxt) >= 0) + return; + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = next) { + IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); + next = p->next; + if (_itimediff(sn, seg->sn) < 0) { + break; + } + else if (sn != seg->sn) { + #ifndef IKCP_FASTACK_CONSERVE + seg->fastack++; + #else + if (_itimediff(ts, seg->ts) >= 0) + seg->fastack++; + #endif + } + } +} + + +//--------------------------------------------------------------------- +// ack append +//--------------------------------------------------------------------- +static void ikcp_ack_push(ikcpcb *kcp, IUINT32 sn, IUINT32 ts) +{ + IUINT32 newsize = kcp->ackcount + 1; + IUINT32 *ptr; + + if (newsize > kcp->ackblock) { + IUINT32 *acklist; + IUINT32 newblock; + + for (newblock = 8; newblock < newsize; newblock <<= 1); + acklist = (IUINT32*)ikcp_malloc(newblock * sizeof(IUINT32) * 2); + + if (acklist == NULL) { + assert(acklist != NULL); + abort(); + } + + if (kcp->acklist != NULL) { + IUINT32 x; + for (x = 0; x < kcp->ackcount; x++) { + acklist[x * 2 + 0] = kcp->acklist[x * 2 + 0]; + acklist[x * 2 + 1] = kcp->acklist[x * 2 + 1]; + } + ikcp_free(kcp->acklist); + } + + kcp->acklist = acklist; + kcp->ackblock = newblock; + } + + ptr = &kcp->acklist[kcp->ackcount * 2]; + ptr[0] = sn; + ptr[1] = ts; + kcp->ackcount++; +} + +static void ikcp_ack_get(const ikcpcb *kcp, int p, IUINT32 *sn, IUINT32 *ts) +{ + if (sn) sn[0] = kcp->acklist[p * 2 + 0]; + if (ts) ts[0] = kcp->acklist[p * 2 + 1]; +} + + +//--------------------------------------------------------------------- +// parse data +//--------------------------------------------------------------------- +void ikcp_parse_data(ikcpcb *kcp, IKCPSEG *newseg) +{ + struct IQUEUEHEAD *p, *prev; + IUINT32 sn = newseg->sn; + int repeat = 0; + + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) >= 0 || + _itimediff(sn, kcp->rcv_nxt) < 0) { + ikcp_segment_delete(kcp, newseg); + return; + } + + for (p = kcp->rcv_buf.prev; p != &kcp->rcv_buf; p = prev) { + IKCPSEG *seg = iqueue_entry(p, IKCPSEG, node); + prev = p->prev; + if (seg->sn == sn) { + repeat = 1; + break; + } + if (_itimediff(sn, seg->sn) > 0) { + break; + } + } + + if (repeat == 0) { + iqueue_init(&newseg->node); + iqueue_add(&newseg->node, p); + kcp->nrcv_buf++; + } else { + ikcp_segment_delete(kcp, newseg); + } + +#if 0 + ikcp_qprint("rcvbuf", &kcp->rcv_buf); + printf("rcv_nxt=%lu\n", kcp->rcv_nxt); +#endif + + // move available data from rcv_buf -> rcv_queue + while (! iqueue_is_empty(&kcp->rcv_buf)) { + IKCPSEG *seg = iqueue_entry(kcp->rcv_buf.next, IKCPSEG, node); + if (seg->sn == kcp->rcv_nxt && kcp->nrcv_que < kcp->rcv_wnd) { + iqueue_del(&seg->node); + kcp->nrcv_buf--; + iqueue_add_tail(&seg->node, &kcp->rcv_queue); + kcp->nrcv_que++; + kcp->rcv_nxt++; + } else { + break; + } + } + +#if 0 + ikcp_qprint("queue", &kcp->rcv_queue); + printf("rcv_nxt=%lu\n", kcp->rcv_nxt); +#endif + +#if 1 +// printf("snd(buf=%d, queue=%d)\n", kcp->nsnd_buf, kcp->nsnd_que); +// printf("rcv(buf=%d, queue=%d)\n", kcp->nrcv_buf, kcp->nrcv_que); +#endif +} + + +//--------------------------------------------------------------------- +// input data +//--------------------------------------------------------------------- +int ikcp_input(ikcpcb *kcp, const char *data, long size) +{ + IUINT32 prev_una = kcp->snd_una; + IUINT32 maxack = 0, latest_ts = 0; + int flag = 0; + + if (ikcp_canlog(kcp, IKCP_LOG_INPUT)) { + ikcp_log(kcp, IKCP_LOG_INPUT, "[RI] %d bytes", (int)size); + } + + if (data == NULL || (int)size < (int)IKCP_OVERHEAD) return -1; + + while (1) { + IUINT32 ts, sn, len, una, conv; + IUINT16 wnd; + IUINT8 cmd, frg; + IKCPSEG *seg; + + if (size < (int)IKCP_OVERHEAD) break; + + data = ikcp_decode32u(data, &conv); + if (conv != kcp->conv) return -1; + + data = ikcp_decode8u(data, &cmd); + data = ikcp_decode8u(data, &frg); + data = ikcp_decode16u(data, &wnd); + data = ikcp_decode32u(data, &ts); + data = ikcp_decode32u(data, &sn); + data = ikcp_decode32u(data, &una); + data = ikcp_decode32u(data, &len); + + size -= IKCP_OVERHEAD; + + if ((long)size < (long)len || (int)len < 0) return -2; + + if (cmd != IKCP_CMD_PUSH && cmd != IKCP_CMD_ACK && + cmd != IKCP_CMD_WASK && cmd != IKCP_CMD_WINS) + return -3; + + kcp->rmt_wnd = wnd; + ikcp_parse_una(kcp, una); + ikcp_shrink_buf(kcp); + + if (cmd == IKCP_CMD_ACK) { + if (_itimediff(kcp->current, ts) >= 0) { + ikcp_update_ack(kcp, _itimediff(kcp->current, ts)); + } + ikcp_parse_ack(kcp, sn); + ikcp_shrink_buf(kcp); + if (flag == 0) { + flag = 1; + maxack = sn; + latest_ts = ts; + } else { + if (_itimediff(sn, maxack) > 0) { + #ifndef IKCP_FASTACK_CONSERVE + maxack = sn; + latest_ts = ts; + #else + if (_itimediff(ts, latest_ts) > 0) { + maxack = sn; + latest_ts = ts; + } + #endif + } + } + if (ikcp_canlog(kcp, IKCP_LOG_IN_ACK)) { + ikcp_log(kcp, IKCP_LOG_IN_ACK, + "input ack: sn=%lu rtt=%ld rto=%ld", (unsigned long)sn, + (long)_itimediff(kcp->current, ts), + (long)kcp->rx_rto); + } + } + else if (cmd == IKCP_CMD_PUSH) { + if (ikcp_canlog(kcp, IKCP_LOG_IN_DATA)) { + ikcp_log(kcp, IKCP_LOG_IN_DATA, + "input psh: sn=%lu ts=%lu", (unsigned long)sn, (unsigned long)ts); + } + if (_itimediff(sn, kcp->rcv_nxt + kcp->rcv_wnd) < 0) { + ikcp_ack_push(kcp, sn, ts); + if (_itimediff(sn, kcp->rcv_nxt) >= 0) { + seg = ikcp_segment_new(kcp, len); + seg->conv = conv; + seg->cmd = cmd; + seg->frg = frg; + seg->wnd = wnd; + seg->ts = ts; + seg->sn = sn; + seg->una = una; + seg->len = len; + + if (len > 0) { + memcpy(seg->data, data, len); + } + + ikcp_parse_data(kcp, seg); + } + } + } + else if (cmd == IKCP_CMD_WASK) { + // ready to send back IKCP_CMD_WINS in ikcp_flush + // tell remote my window size + kcp->probe |= IKCP_ASK_TELL; + if (ikcp_canlog(kcp, IKCP_LOG_IN_PROBE)) { + ikcp_log(kcp, IKCP_LOG_IN_PROBE, "input probe"); + } + } + else if (cmd == IKCP_CMD_WINS) { + // do nothing + if (ikcp_canlog(kcp, IKCP_LOG_IN_WINS)) { + ikcp_log(kcp, IKCP_LOG_IN_WINS, + "input wins: %lu", (unsigned long)(wnd)); + } + } + else { + return -3; + } + + data += len; + size -= len; + } + + if (flag != 0) { + ikcp_parse_fastack(kcp, maxack, latest_ts); + } + + if (_itimediff(kcp->snd_una, prev_una) > 0) { + if (kcp->cwnd < kcp->rmt_wnd) { + IUINT32 mss = kcp->mss; + if (kcp->cwnd < kcp->ssthresh) { + kcp->cwnd++; + kcp->incr += mss; + } else { + if (kcp->incr < mss) kcp->incr = mss; + kcp->incr += (mss * mss) / kcp->incr + (mss / 16); + if ((kcp->cwnd + 1) * mss <= kcp->incr) { + #if 1 + kcp->cwnd = (kcp->incr + mss - 1) / ((mss > 0)? mss : 1); + #else + kcp->cwnd++; + #endif + } + } + if (kcp->cwnd > kcp->rmt_wnd) { + kcp->cwnd = kcp->rmt_wnd; + kcp->incr = kcp->rmt_wnd * mss; + } + } + } + + return 0; +} + + +//--------------------------------------------------------------------- +// ikcp_encode_seg +//--------------------------------------------------------------------- +static char *ikcp_encode_seg(char *ptr, const IKCPSEG *seg) +{ + ptr = ikcp_encode32u(ptr, seg->conv); + ptr = ikcp_encode8u(ptr, (IUINT8)seg->cmd); + ptr = ikcp_encode8u(ptr, (IUINT8)seg->frg); + ptr = ikcp_encode16u(ptr, (IUINT16)seg->wnd); + ptr = ikcp_encode32u(ptr, seg->ts); + ptr = ikcp_encode32u(ptr, seg->sn); + ptr = ikcp_encode32u(ptr, seg->una); + ptr = ikcp_encode32u(ptr, seg->len); + return ptr; +} + +static int ikcp_wnd_unused(const ikcpcb *kcp) +{ + if (kcp->nrcv_que < kcp->rcv_wnd) { + return kcp->rcv_wnd - kcp->nrcv_que; + } + return 0; +} + + +//--------------------------------------------------------------------- +// ikcp_flush +//--------------------------------------------------------------------- +void ikcp_flush(ikcpcb *kcp) +{ + IUINT32 current = kcp->current; + char *buffer = kcp->buffer; + char *ptr = buffer; + int count, size, i; + IUINT32 resent, cwnd; + IUINT32 rtomin; + struct IQUEUEHEAD *p; + int change = 0; + int lost = 0; + IKCPSEG seg; + + // 'ikcp_update' haven't been called. + if (kcp->updated == 0) return; + + seg.conv = kcp->conv; + seg.cmd = IKCP_CMD_ACK; + seg.frg = 0; + seg.wnd = ikcp_wnd_unused(kcp); + seg.una = kcp->rcv_nxt; + seg.len = 0; + seg.sn = 0; + seg.ts = 0; + + // flush acknowledges + count = kcp->ackcount; + for (i = 0; i < count; i++) { + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { + ikcp_output(kcp, buffer, size); + ptr = buffer; + } + ikcp_ack_get(kcp, i, &seg.sn, &seg.ts); + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->ackcount = 0; + + // probe window size (if remote window size equals zero) + if (kcp->rmt_wnd == 0) { + if (kcp->probe_wait == 0) { + kcp->probe_wait = IKCP_PROBE_INIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + } + else { + if (_itimediff(kcp->current, kcp->ts_probe) >= 0) { + if (kcp->probe_wait < IKCP_PROBE_INIT) + kcp->probe_wait = IKCP_PROBE_INIT; + kcp->probe_wait += kcp->probe_wait / 2; + if (kcp->probe_wait > IKCP_PROBE_LIMIT) + kcp->probe_wait = IKCP_PROBE_LIMIT; + kcp->ts_probe = kcp->current + kcp->probe_wait; + kcp->probe |= IKCP_ASK_SEND; + } + } + } else { + kcp->ts_probe = 0; + kcp->probe_wait = 0; + } + + // flush window probing commands + if (kcp->probe & IKCP_ASK_SEND) { + seg.cmd = IKCP_CMD_WASK; + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { + ikcp_output(kcp, buffer, size); + ptr = buffer; + } + ptr = ikcp_encode_seg(ptr, &seg); + } + + // flush window probing commands + if (kcp->probe & IKCP_ASK_TELL) { + seg.cmd = IKCP_CMD_WINS; + size = (int)(ptr - buffer); + if (size + (int)IKCP_OVERHEAD > (int)kcp->mtu) { + ikcp_output(kcp, buffer, size); + ptr = buffer; + } + ptr = ikcp_encode_seg(ptr, &seg); + } + + kcp->probe = 0; + + // calculate window size + cwnd = _imin_(kcp->snd_wnd, kcp->rmt_wnd); + if (kcp->nocwnd == 0) cwnd = _imin_(kcp->cwnd, cwnd); + + // move data from snd_queue to snd_buf + while (_itimediff(kcp->snd_nxt, kcp->snd_una + cwnd) < 0) { + IKCPSEG *newseg; + if (iqueue_is_empty(&kcp->snd_queue)) break; + + newseg = iqueue_entry(kcp->snd_queue.next, IKCPSEG, node); + + iqueue_del(&newseg->node); + iqueue_add_tail(&newseg->node, &kcp->snd_buf); + kcp->nsnd_que--; + kcp->nsnd_buf++; + + newseg->conv = kcp->conv; + newseg->cmd = IKCP_CMD_PUSH; + newseg->wnd = seg.wnd; + newseg->ts = current; + newseg->sn = kcp->snd_nxt++; + newseg->una = kcp->rcv_nxt; + newseg->resendts = current; + newseg->rto = kcp->rx_rto; + newseg->fastack = 0; + newseg->xmit = 0; + } + + // calculate resent + resent = (kcp->fastresend > 0)? (IUINT32)kcp->fastresend : 0xffffffff; + rtomin = (kcp->nodelay == 0)? (kcp->rx_rto >> 3) : 0; + + // flush data segments + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { + IKCPSEG *segment = iqueue_entry(p, IKCPSEG, node); + int needsend = 0; + if (segment->xmit == 0) { + needsend = 1; + segment->xmit++; + segment->rto = kcp->rx_rto; + segment->resendts = current + segment->rto + rtomin; + } + else if (_itimediff(current, segment->resendts) >= 0) { + needsend = 1; + segment->xmit++; + kcp->xmit++; + if (kcp->nodelay == 0) { + segment->rto += _imax_(segment->rto, (IUINT32)kcp->rx_rto); + } else { + IINT32 step = (kcp->nodelay < 2)? + ((IINT32)(segment->rto)) : kcp->rx_rto; + segment->rto += step / 2; + } + segment->resendts = current + segment->rto; + lost = 1; + } + else if (segment->fastack >= resent) { + if ((int)segment->xmit <= kcp->fastlimit || + kcp->fastlimit <= 0) { + needsend = 1; + segment->xmit++; + segment->fastack = 0; + segment->resendts = current + segment->rto; + change++; + } + } + + if (needsend) { + int need; + segment->ts = current; + segment->wnd = seg.wnd; + segment->una = kcp->rcv_nxt; + + size = (int)(ptr - buffer); + need = IKCP_OVERHEAD + segment->len; + + if (size + need > (int)kcp->mtu) { + ikcp_output(kcp, buffer, size); + ptr = buffer; + } + + ptr = ikcp_encode_seg(ptr, segment); + + if (segment->len > 0) { + memcpy(ptr, segment->data, segment->len); + ptr += segment->len; + } + + if (segment->xmit >= kcp->dead_link) { + kcp->state = (IUINT32)-1; + } + } + } + + // flash remain segments + size = (int)(ptr - buffer); + if (size > 0) { + ikcp_output(kcp, buffer, size); + } + + // update ssthresh + if (change) { + IUINT32 inflight = kcp->snd_nxt - kcp->snd_una; + kcp->ssthresh = inflight / 2; + if (kcp->ssthresh < IKCP_THRESH_MIN) + kcp->ssthresh = IKCP_THRESH_MIN; + kcp->cwnd = kcp->ssthresh + resent; + kcp->incr = kcp->cwnd * kcp->mss; + } + + if (lost) { + kcp->ssthresh = cwnd / 2; + if (kcp->ssthresh < IKCP_THRESH_MIN) + kcp->ssthresh = IKCP_THRESH_MIN; + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } + + if (kcp->cwnd < 1) { + kcp->cwnd = 1; + kcp->incr = kcp->mss; + } +} + + +//--------------------------------------------------------------------- +// update state (call it repeatedly, every 10ms-100ms), or you can ask +// ikcp_check when to call it again (without ikcp_input/_send calling). +// 'current' - current timestamp in millisec. +//--------------------------------------------------------------------- +void ikcp_update(ikcpcb *kcp, IUINT32 current) +{ + IINT32 slap; + + kcp->current = current; + + if (kcp->updated == 0) { + kcp->updated = 1; + kcp->ts_flush = kcp->current; + } + + slap = _itimediff(kcp->current, kcp->ts_flush); + + if (slap >= 10000 || slap < -10000) { + kcp->ts_flush = kcp->current; + slap = 0; + } + + if (slap >= 0) { + kcp->ts_flush += kcp->interval; + if (_itimediff(kcp->current, kcp->ts_flush) >= 0) { + kcp->ts_flush = kcp->current + kcp->interval; + } + ikcp_flush(kcp); + } +} + + +//--------------------------------------------------------------------- +// Determine when should you invoke ikcp_update: +// returns when you should invoke ikcp_update in millisec, if there +// is no ikcp_input/_send calling. you can call ikcp_update in that +// time, instead of call update repeatly. +// Important to reduce unnacessary ikcp_update invoking. use it to +// schedule ikcp_update (eg. implementing an epoll-like mechanism, +// or optimize ikcp_update when handling massive kcp connections) +//--------------------------------------------------------------------- +IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current) +{ + IUINT32 ts_flush = kcp->ts_flush; + IINT32 tm_flush = 0x7fffffff; + IINT32 tm_packet = 0x7fffffff; + IUINT32 minimal = 0; + struct IQUEUEHEAD *p; + + if (kcp->updated == 0) { + return current; + } + + if (_itimediff(current, ts_flush) >= 10000 || + _itimediff(current, ts_flush) < -10000) { + ts_flush = current; + } + + if (_itimediff(current, ts_flush) >= 0) { + return current; + } + + tm_flush = _itimediff(ts_flush, current); + + for (p = kcp->snd_buf.next; p != &kcp->snd_buf; p = p->next) { + const IKCPSEG *seg = iqueue_entry(p, const IKCPSEG, node); + IINT32 diff = _itimediff(seg->resendts, current); + if (diff <= 0) { + return current; + } + if (diff < tm_packet) tm_packet = diff; + } + + minimal = (IUINT32)(tm_packet < tm_flush ? tm_packet : tm_flush); + if (minimal >= kcp->interval) minimal = kcp->interval; + + return current + minimal; +} + + + +int ikcp_setmtu(ikcpcb *kcp, int mtu) +{ + char *buffer; + if (mtu < 50 || mtu < (int)IKCP_OVERHEAD) + return -1; + buffer = (char*)ikcp_malloc((mtu + IKCP_OVERHEAD) * 3); + if (buffer == NULL) + return -2; + kcp->mtu = mtu; + kcp->mss = kcp->mtu - IKCP_OVERHEAD; + ikcp_free(kcp->buffer); + kcp->buffer = buffer; + return 0; +} + +int ikcp_interval(ikcpcb *kcp, int interval) +{ + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + kcp->interval = interval; + return 0; +} + +int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc) +{ + if (nodelay >= 0) { + kcp->nodelay = nodelay; + if (nodelay) { + kcp->rx_minrto = IKCP_RTO_NDL; + } + else { + kcp->rx_minrto = IKCP_RTO_MIN; + } + } + if (interval >= 0) { + if (interval > 5000) interval = 5000; + else if (interval < 10) interval = 10; + kcp->interval = interval; + } + if (resend >= 0) { + kcp->fastresend = resend; + } + if (nc >= 0) { + kcp->nocwnd = nc; + } + return 0; +} + + +int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd) +{ + if (kcp) { + if (sndwnd > 0) { + kcp->snd_wnd = sndwnd; + } + if (rcvwnd > 0) { // must >= max fragment size + kcp->rcv_wnd = _imax_(rcvwnd, IKCP_WND_RCV); + } + } + return 0; +} + +int ikcp_waitsnd(const ikcpcb *kcp) +{ + return kcp->nsnd_buf + kcp->nsnd_que; +} + + +// read conv +IUINT32 ikcp_getconv(const void *ptr) +{ + IUINT32 conv; + ikcp_decode32u((const char*)ptr, &conv); + return conv; +} + + diff --git a/external/libhv/libhv-1.3.2/event/kcp/ikcp.h b/external/libhv/libhv-1.3.2/event/kcp/ikcp.h new file mode 100644 index 0000000..e525105 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kcp/ikcp.h @@ -0,0 +1,416 @@ +//===================================================================== +// +// KCP - A Better ARQ Protocol Implementation +// skywind3000 (at) gmail.com, 2010-2011 +// +// Features: +// + Average RTT reduce 30% - 40% vs traditional ARQ like tcp. +// + Maximum RTT reduce three times vs tcp. +// + Lightweight, distributed as a single source file. +// +//===================================================================== +#ifndef __IKCP_H__ +#define __IKCP_H__ + +#include +#include +#include + + +//===================================================================== +// 32BIT INTEGER DEFINITION +//===================================================================== +#ifndef __INTEGER_32_BITS__ +#define __INTEGER_32_BITS__ +#if defined(_WIN64) || defined(WIN64) || defined(__amd64__) || \ + defined(__x86_64) || defined(__x86_64__) || defined(_M_IA64) || \ + defined(_M_AMD64) + typedef unsigned int ISTDUINT32; + typedef int ISTDINT32; +#elif defined(_WIN32) || defined(WIN32) || defined(__i386__) || \ + defined(__i386) || defined(_M_X86) + typedef unsigned long ISTDUINT32; + typedef long ISTDINT32; +#elif defined(__MACOS__) + typedef UInt32 ISTDUINT32; + typedef SInt32 ISTDINT32; +#elif defined(__APPLE__) && defined(__MACH__) + #include + typedef u_int32_t ISTDUINT32; + typedef int32_t ISTDINT32; +#elif defined(__BEOS__) + #include + typedef u_int32_t ISTDUINT32; + typedef int32_t ISTDINT32; +#elif (defined(_MSC_VER) || defined(__BORLANDC__)) && (!defined(__MSDOS__)) + typedef unsigned __int32 ISTDUINT32; + typedef __int32 ISTDINT32; +#elif defined(__GNUC__) + #include + typedef uint32_t ISTDUINT32; + typedef int32_t ISTDINT32; +#else + typedef unsigned long ISTDUINT32; + typedef long ISTDINT32; +#endif +#endif + + +//===================================================================== +// Integer Definition +//===================================================================== +#ifndef __IINT8_DEFINED +#define __IINT8_DEFINED +typedef char IINT8; +#endif + +#ifndef __IUINT8_DEFINED +#define __IUINT8_DEFINED +typedef unsigned char IUINT8; +#endif + +#ifndef __IUINT16_DEFINED +#define __IUINT16_DEFINED +typedef unsigned short IUINT16; +#endif + +#ifndef __IINT16_DEFINED +#define __IINT16_DEFINED +typedef short IINT16; +#endif + +#ifndef __IINT32_DEFINED +#define __IINT32_DEFINED +typedef ISTDINT32 IINT32; +#endif + +#ifndef __IUINT32_DEFINED +#define __IUINT32_DEFINED +typedef ISTDUINT32 IUINT32; +#endif + +#ifndef __IINT64_DEFINED +#define __IINT64_DEFINED +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef __int64 IINT64; +#else +typedef long long IINT64; +#endif +#endif + +#ifndef __IUINT64_DEFINED +#define __IUINT64_DEFINED +#if defined(_MSC_VER) || defined(__BORLANDC__) +typedef unsigned __int64 IUINT64; +#else +typedef unsigned long long IUINT64; +#endif +#endif + +#ifndef INLINE +#if defined(__GNUC__) + +#if (__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)) +#define INLINE __inline__ __attribute__((always_inline)) +#else +#define INLINE __inline__ +#endif + +#elif (defined(_MSC_VER) || defined(__BORLANDC__) || defined(__WATCOMC__)) +#define INLINE __inline +#else +#define INLINE +#endif +#endif + +#if (!defined(__cplusplus)) && (!defined(inline)) +#define inline INLINE +#endif + + +//===================================================================== +// QUEUE DEFINITION +//===================================================================== +#ifndef __IQUEUE_DEF__ +#define __IQUEUE_DEF__ + +struct IQUEUEHEAD { + struct IQUEUEHEAD *next, *prev; +}; + +typedef struct IQUEUEHEAD iqueue_head; + + +//--------------------------------------------------------------------- +// queue init +//--------------------------------------------------------------------- +#define IQUEUE_HEAD_INIT(name) { &(name), &(name) } +#define IQUEUE_HEAD(name) \ + struct IQUEUEHEAD name = IQUEUE_HEAD_INIT(name) + +#define IQUEUE_INIT(ptr) ( \ + (ptr)->next = (ptr), (ptr)->prev = (ptr)) + +#define IOFFSETOF(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) + +#define ICONTAINEROF(ptr, type, member) ( \ + (type*)( ((char*)((type*)ptr)) - IOFFSETOF(type, member)) ) + +#define IQUEUE_ENTRY(ptr, type, member) ICONTAINEROF(ptr, type, member) + + +//--------------------------------------------------------------------- +// queue operation +//--------------------------------------------------------------------- +#define IQUEUE_ADD(node, head) ( \ + (node)->prev = (head), (node)->next = (head)->next, \ + (head)->next->prev = (node), (head)->next = (node)) + +#define IQUEUE_ADD_TAIL(node, head) ( \ + (node)->prev = (head)->prev, (node)->next = (head), \ + (head)->prev->next = (node), (head)->prev = (node)) + +#define IQUEUE_DEL_BETWEEN(p, n) ((n)->prev = (p), (p)->next = (n)) + +#define IQUEUE_DEL(entry) (\ + (entry)->next->prev = (entry)->prev, \ + (entry)->prev->next = (entry)->next, \ + (entry)->next = 0, (entry)->prev = 0) + +#define IQUEUE_DEL_INIT(entry) do { \ + IQUEUE_DEL(entry); IQUEUE_INIT(entry); } while (0) + +#define IQUEUE_IS_EMPTY(entry) ((entry) == (entry)->next) + +#define iqueue_init IQUEUE_INIT +#define iqueue_entry IQUEUE_ENTRY +#define iqueue_add IQUEUE_ADD +#define iqueue_add_tail IQUEUE_ADD_TAIL +#define iqueue_del IQUEUE_DEL +#define iqueue_del_init IQUEUE_DEL_INIT +#define iqueue_is_empty IQUEUE_IS_EMPTY + +#define IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) \ + for ((iterator) = iqueue_entry((head)->next, TYPE, MEMBER); \ + &((iterator)->MEMBER) != (head); \ + (iterator) = iqueue_entry((iterator)->MEMBER.next, TYPE, MEMBER)) + +#define iqueue_foreach(iterator, head, TYPE, MEMBER) \ + IQUEUE_FOREACH(iterator, head, TYPE, MEMBER) + +#define iqueue_foreach_entry(pos, head) \ + for( (pos) = (head)->next; (pos) != (head) ; (pos) = (pos)->next ) + + +#define __iqueue_splice(list, head) do { \ + iqueue_head *first = (list)->next, *last = (list)->prev; \ + iqueue_head *at = (head)->next; \ + (first)->prev = (head), (head)->next = (first); \ + (last)->next = (at), (at)->prev = (last); } while (0) + +#define iqueue_splice(list, head) do { \ + if (!iqueue_is_empty(list)) __iqueue_splice(list, head); } while (0) + +#define iqueue_splice_init(list, head) do { \ + iqueue_splice(list, head); iqueue_init(list); } while (0) + + +#ifdef _MSC_VER +#pragma warning(disable:4311) +#pragma warning(disable:4312) +#pragma warning(disable:4996) +#endif + +#endif + + +//--------------------------------------------------------------------- +// BYTE ORDER & ALIGNMENT +//--------------------------------------------------------------------- +#ifndef IWORDS_BIG_ENDIAN + #ifdef _BIG_ENDIAN_ + #if _BIG_ENDIAN_ + #define IWORDS_BIG_ENDIAN 1 + #endif + #endif + #ifndef IWORDS_BIG_ENDIAN + #if defined(__hppa__) || \ + defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \ + (defined(__MIPS__) && defined(__MIPSEB__)) || \ + defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \ + defined(__sparc__) || defined(__powerpc__) || \ + defined(__mc68000__) || defined(__s390x__) || defined(__s390__) + #define IWORDS_BIG_ENDIAN 1 + #endif + #endif + #ifndef IWORDS_BIG_ENDIAN + #define IWORDS_BIG_ENDIAN 0 + #endif +#endif + +#ifndef IWORDS_MUST_ALIGN + #if defined(__i386__) || defined(__i386) || defined(_i386_) + #define IWORDS_MUST_ALIGN 0 + #elif defined(_M_IX86) || defined(_X86_) || defined(__x86_64__) + #define IWORDS_MUST_ALIGN 0 + #elif defined(__amd64) || defined(__amd64__) + #define IWORDS_MUST_ALIGN 0 + #else + #define IWORDS_MUST_ALIGN 1 + #endif +#endif + + +//===================================================================== +// SEGMENT +//===================================================================== +struct IKCPSEG +{ + struct IQUEUEHEAD node; + IUINT32 conv; + IUINT32 cmd; + IUINT32 frg; + IUINT32 wnd; + IUINT32 ts; + IUINT32 sn; + IUINT32 una; + IUINT32 len; + IUINT32 resendts; + IUINT32 rto; + IUINT32 fastack; + IUINT32 xmit; + char data[1]; +}; + + +//--------------------------------------------------------------------- +// IKCPCB +//--------------------------------------------------------------------- +struct IKCPCB +{ + IUINT32 conv, mtu, mss, state; + IUINT32 snd_una, snd_nxt, rcv_nxt; + IUINT32 ts_recent, ts_lastack, ssthresh; + IINT32 rx_rttval, rx_srtt, rx_rto, rx_minrto; + IUINT32 snd_wnd, rcv_wnd, rmt_wnd, cwnd, probe; + IUINT32 current, interval, ts_flush, xmit; + IUINT32 nrcv_buf, nsnd_buf; + IUINT32 nrcv_que, nsnd_que; + IUINT32 nodelay, updated; + IUINT32 ts_probe, probe_wait; + IUINT32 dead_link, incr; + struct IQUEUEHEAD snd_queue; + struct IQUEUEHEAD rcv_queue; + struct IQUEUEHEAD snd_buf; + struct IQUEUEHEAD rcv_buf; + IUINT32 *acklist; + IUINT32 ackcount; + IUINT32 ackblock; + void *user; + char *buffer; + int fastresend; + int fastlimit; + int nocwnd, stream; + int logmask; + int (*output)(const char *buf, int len, struct IKCPCB *kcp, void *user); + void (*writelog)(const char *log, struct IKCPCB *kcp, void *user); +}; + + +typedef struct IKCPCB ikcpcb; + +#define IKCP_LOG_OUTPUT 1 +#define IKCP_LOG_INPUT 2 +#define IKCP_LOG_SEND 4 +#define IKCP_LOG_RECV 8 +#define IKCP_LOG_IN_DATA 16 +#define IKCP_LOG_IN_ACK 32 +#define IKCP_LOG_IN_PROBE 64 +#define IKCP_LOG_IN_WINS 128 +#define IKCP_LOG_OUT_DATA 256 +#define IKCP_LOG_OUT_ACK 512 +#define IKCP_LOG_OUT_PROBE 1024 +#define IKCP_LOG_OUT_WINS 2048 + +#ifdef __cplusplus +extern "C" { +#endif + +//--------------------------------------------------------------------- +// interface +//--------------------------------------------------------------------- + +// create a new kcp control object, 'conv' must equal in two endpoint +// from the same connection. 'user' will be passed to the output callback +// output callback can be setup like this: 'kcp->output = my_udp_output' +ikcpcb* ikcp_create(IUINT32 conv, void *user); + +// release kcp control object +void ikcp_release(ikcpcb *kcp); + +// set output callback, which will be invoked by kcp +void ikcp_setoutput(ikcpcb *kcp, int (*output)(const char *buf, int len, + ikcpcb *kcp, void *user)); + +// user/upper level recv: returns size, returns below zero for EAGAIN +int ikcp_recv(ikcpcb *kcp, char *buffer, int len); + +// user/upper level send, returns below zero for error +int ikcp_send(ikcpcb *kcp, const char *buffer, int len); + +// update state (call it repeatedly, every 10ms-100ms), or you can ask +// ikcp_check when to call it again (without ikcp_input/_send calling). +// 'current' - current timestamp in millisec. +void ikcp_update(ikcpcb *kcp, IUINT32 current); + +// Determine when should you invoke ikcp_update: +// returns when you should invoke ikcp_update in millisec, if there +// is no ikcp_input/_send calling. you can call ikcp_update in that +// time, instead of call update repeatly. +// Important to reduce unnacessary ikcp_update invoking. use it to +// schedule ikcp_update (eg. implementing an epoll-like mechanism, +// or optimize ikcp_update when handling massive kcp connections) +IUINT32 ikcp_check(const ikcpcb *kcp, IUINT32 current); + +// when you received a low level packet (eg. UDP packet), call it +int ikcp_input(ikcpcb *kcp, const char *data, long size); + +// flush pending data +void ikcp_flush(ikcpcb *kcp); + +// check the size of next message in the recv queue +int ikcp_peeksize(const ikcpcb *kcp); + +// change MTU size, default is 1400 +int ikcp_setmtu(ikcpcb *kcp, int mtu); + +// set maximum window size: sndwnd=32, rcvwnd=32 by default +int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd); + +// get how many packet is waiting to be sent +int ikcp_waitsnd(const ikcpcb *kcp); + +// fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) +// nodelay: 0:disable(default), 1:enable +// interval: internal update timer interval in millisec, default is 100ms +// resend: 0:disable fast resend(default), 1:enable fast resend +// nc: 0:normal congestion control(default), 1:disable congestion control +int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc); + + +void ikcp_log(ikcpcb *kcp, int mask, const char *fmt, ...); + +// setup allocator +void ikcp_allocator(void* (*new_malloc)(size_t), void (*new_free)(void*)); + +// read conv +IUINT32 ikcp_getconv(const void *ptr); + + +#ifdef __cplusplus +} +#endif + +#endif + + diff --git a/external/libhv/libhv-1.3.2/event/kqueue.c b/external/libhv/libhv-1.3.2/event/kqueue.c new file mode 100644 index 0000000..5416280 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/kqueue.c @@ -0,0 +1,174 @@ +#include "iowatcher.h" + +#ifdef EVENT_KQUEUE +#include "hplatform.h" +#include "hdef.h" + +#include + +#include "hevent.h" + +#define EVENTS_INIT_SIZE 64 + +#define READ_INDEX 0 +#define WRITE_INDEX 1 +#define EVENT_INDEX(type) ((type == EVFILT_READ) ? READ_INDEX : WRITE_INDEX) + +typedef struct kqueue_ctx_s { + int kqfd; + int capacity; + int nchanges; + struct kevent* changes; + //int nevents; // nevents == nchanges + struct kevent* events; +} kqueue_ctx_t; + +static void kqueue_ctx_resize(kqueue_ctx_t* kqueue_ctx, int size) { + int bytes = sizeof(struct kevent) * size; + int oldbytes = sizeof(struct kevent) * kqueue_ctx->capacity; + kqueue_ctx->changes = (struct kevent*)hv_realloc(kqueue_ctx->changes, bytes, oldbytes); + kqueue_ctx->events = (struct kevent*)hv_realloc(kqueue_ctx->events, bytes, oldbytes); + kqueue_ctx->capacity = size; +} + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + kqueue_ctx_t* kqueue_ctx; + HV_ALLOC_SIZEOF(kqueue_ctx); + kqueue_ctx->kqfd = kqueue(); + kqueue_ctx->capacity = EVENTS_INIT_SIZE; + kqueue_ctx->nchanges = 0; + int bytes = sizeof(struct kevent) * kqueue_ctx->capacity; + HV_ALLOC(kqueue_ctx->changes, bytes); + HV_ALLOC(kqueue_ctx->events, bytes); + loop->iowatcher = kqueue_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + if (loop->iowatcher == NULL) return 0; + kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; + close(kqueue_ctx->kqfd); + HV_FREE(kqueue_ctx->changes); + HV_FREE(kqueue_ctx->events); + HV_FREE(loop->iowatcher); + return 0; +} + +static int __add_event(hloop_t* loop, int fd, int event) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; + hio_t* io = loop->ios.ptr[fd]; + int idx = io->event_index[EVENT_INDEX(event)]; + if (idx < 0) { + io->event_index[EVENT_INDEX(event)] = idx = kqueue_ctx->nchanges; + kqueue_ctx->nchanges++; + if (idx == kqueue_ctx->capacity) { + kqueue_ctx_resize(kqueue_ctx, kqueue_ctx->capacity*2); + } + memset(kqueue_ctx->changes+idx, 0, sizeof(struct kevent)); + kqueue_ctx->changes[idx].ident = fd; + } + assert(kqueue_ctx->changes[idx].ident == fd); + kqueue_ctx->changes[idx].filter = event; + kqueue_ctx->changes[idx].flags = EV_ADD|EV_ENABLE; + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, NULL, 0, &ts); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (events & HV_READ) { + __add_event(loop, fd, EVFILT_READ); + } + if (events & HV_WRITE) { + __add_event(loop, fd, EVFILT_WRITE); + } + return 0; +} + +static int __del_event(hloop_t* loop, int fd, int event) { + kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; + if (kqueue_ctx == NULL) return 0; + hio_t* io = loop->ios.ptr[fd]; + int idx = io->event_index[EVENT_INDEX(event)]; + if (idx < 0) return 0; + assert(kqueue_ctx->changes[idx].ident == fd); + kqueue_ctx->changes[idx].flags = EV_DELETE; + io->event_index[EVENT_INDEX(event)] = -1; + int lastidx = kqueue_ctx->nchanges - 1; + if (idx < lastidx) { + // swap + struct kevent tmp; + tmp = kqueue_ctx->changes[idx]; + kqueue_ctx->changes[idx] = kqueue_ctx->changes[lastidx]; + kqueue_ctx->changes[lastidx] = tmp; + hio_t* last = loop->ios.ptr[kqueue_ctx->changes[idx].ident]; + if (last) { + last->event_index[EVENT_INDEX(kqueue_ctx->changes[idx].filter)] = idx; + } + } + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, NULL, 0, &ts); + kqueue_ctx->nchanges--; + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + if (events & HV_READ) { + __del_event(loop, fd, EVFILT_READ); + } + if (events & HV_WRITE) { + __del_event(loop, fd, EVFILT_WRITE); + } + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + kqueue_ctx_t* kqueue_ctx = (kqueue_ctx_t*)loop->iowatcher; + if (kqueue_ctx == NULL) return 0; + if (kqueue_ctx->nchanges == 0) return 0; + struct timespec ts, *tp; + if (timeout == INFINITE) { + tp = NULL; + } + else { + ts.tv_sec = timeout / 1000; + ts.tv_nsec = (timeout % 1000) * 1000000; + tp = &ts; + } + int nkqueue = kevent(kqueue_ctx->kqfd, kqueue_ctx->changes, kqueue_ctx->nchanges, kqueue_ctx->events, kqueue_ctx->nchanges, tp); + if (nkqueue < 0) { + perror("kevent"); + return nkqueue; + } + if (nkqueue == 0) return 0; + int nevents = 0; + for (int i = 0; i < nkqueue; ++i) { + if (kqueue_ctx->events[i].flags & EV_ERROR) { + continue; + } + ++nevents; + int fd = kqueue_ctx->events[i].ident; + int revents = kqueue_ctx->events[i].filter; + hio_t* io = loop->ios.ptr[fd]; + if (io) { + if (revents & EVFILT_READ) { + io->revents |= HV_READ; + } + if (revents & EVFILT_WRITE) { + io->revents |= HV_WRITE; + } + EVENT_PENDING(io); + } + if (nevents == nkqueue) break; + } + return nevents; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/nio.c b/external/libhv/libhv-1.3.2/event/nio.c new file mode 100644 index 0000000..4ae5cc7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/nio.c @@ -0,0 +1,602 @@ +#include "iowatcher.h" +#ifndef EVENT_IOCP +#include "hevent.h" +#include "hsocket.h" +#include "hssl.h" +#include "hlog.h" +#include "herr.h" +#include "hthread.h" + +static void __connect_timeout_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + if (io) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + hlogw("connect timeout [%s] <=> [%s]", + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + io->error = ETIMEDOUT; + hio_close(io); + } +} + +static void __close_timeout_cb(htimer_t* timer) { + hio_t* io = (hio_t*)timer->privdata; + if (io) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + hlogw("close timeout [%s] <=> [%s]", + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + io->error = ETIMEDOUT; + hio_close(io); + } +} + +static void __accept_cb(hio_t* io) { + hio_accept_cb(io); +} + +static void __connect_cb(hio_t* io) { + hio_del_connect_timer(io); + hio_connect_cb(io); +} + +static void __read_cb(hio_t* io, void* buf, int readbytes) { + // printd("> %.*s\n", readbytes, buf); + io->last_read_hrtime = io->loop->cur_hrtime; + hio_handle_read(io, buf, readbytes); +} + +static void __write_cb(hio_t* io, const void* buf, int writebytes) { + // printd("< %.*s\n", writebytes, buf); + io->last_write_hrtime = io->loop->cur_hrtime; + hio_write_cb(io, buf, writebytes); +} + +static void __close_cb(hio_t* io) { + // printd("close fd=%d\n", io->fd); + hio_del_connect_timer(io); + hio_del_close_timer(io); + hio_del_read_timer(io); + hio_del_write_timer(io); + hio_del_keepalive_timer(io); + hio_del_heartbeat_timer(io); + hio_close_cb(io); +} + +static void ssl_server_handshake(hio_t* io) { + printd("ssl server handshake...\n"); + int ret = hssl_accept(io->ssl); + if (ret == 0) { + // handshake finish + hio_del(io, HV_READ); + printd("ssl handshake finished.\n"); + __accept_cb(io); + } + else if (ret == HSSL_WANT_READ) { + if ((io->events & HV_READ) == 0) { + hio_add(io, ssl_server_handshake, HV_READ); + } + } + else { + hloge("ssl handshake failed: %d", ret); + io->error = ERR_SSL_HANDSHAKE; + hio_close(io); + } +} + +static void ssl_client_handshake(hio_t* io) { + printd("ssl client handshake...\n"); + int ret = hssl_connect(io->ssl); + if (ret == 0) { + // handshake finish + hio_del(io, HV_READ); + printd("ssl handshake finished.\n"); + __connect_cb(io); + } + else if (ret == HSSL_WANT_READ) { + if ((io->events & HV_READ) == 0) { + hio_add(io, ssl_client_handshake, HV_READ); + } + } + else { + hloge("ssl handshake failed: %d", ret); + io->error = ERR_SSL_HANDSHAKE; + hio_close(io); + } +} + +static void nio_accept(hio_t* io) { + // printd("nio_accept listenfd=%d\n", io->fd); + int connfd = 0, err = 0, accept_cnt = 0; + socklen_t addrlen; + hio_t* connio = NULL; + while (accept_cnt++ < 3) { + addrlen = sizeof(sockaddr_u); + connfd = accept(io->fd, io->peeraddr, &addrlen); + if (connfd < 0) { + err = socket_errno(); + if (err == EAGAIN || err == EINTR) { + return; + } else { + perror("accept"); + io->error = err; + goto accept_error; + } + } + addrlen = sizeof(sockaddr_u); + getsockname(connfd, io->localaddr, &addrlen); + connio = hio_get(io->loop, connfd); + // NOTE: inherit from listenio + connio->accept_cb = io->accept_cb; + connio->userdata = io->userdata; + if (io->unpack_setting) { + hio_set_unpack(connio, io->unpack_setting); + } + + if (io->io_type == HIO_TYPE_SSL) { + if (connio->ssl == NULL) { + // io->ssl_ctx > g_ssl_ctx > hssl_ctx_new + hssl_ctx_t ssl_ctx = NULL; + if (io->ssl_ctx) { + ssl_ctx = io->ssl_ctx; + } else if (g_ssl_ctx) { + ssl_ctx = g_ssl_ctx; + } else { + io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); + io->alloced_ssl_ctx = 1; + } + if (ssl_ctx == NULL) { + io->error = ERR_NEW_SSL_CTX; + goto accept_error; + } + hssl_t ssl = hssl_new(ssl_ctx, connfd); + if (ssl == NULL) { + io->error = ERR_NEW_SSL; + goto accept_error; + } + connio->ssl = ssl; + } + hio_enable_ssl(connio); + ssl_server_handshake(connio); + } + else { + // NOTE: SSL call accept_cb after handshake finished + __accept_cb(connio); + } + } + return; + +accept_error: + hloge("listenfd=%d accept error: %s:%d", io->fd, socket_strerror(io->error), io->error); + // NOTE: Don't close listen fd automatically anyway. + // hio_close(io); +} + +static void nio_connect(hio_t* io) { + // printd("nio_connect connfd=%d\n", io->fd); + socklen_t addrlen = sizeof(sockaddr_u); + int ret = getpeername(io->fd, io->peeraddr, &addrlen); + if (ret < 0) { + io->error = socket_errno(); + goto connect_error; + } + else { + addrlen = sizeof(sockaddr_u); + getsockname(io->fd, io->localaddr, &addrlen); + + if (io->io_type == HIO_TYPE_SSL) { + if (io->ssl == NULL) { + // io->ssl_ctx > g_ssl_ctx > hssl_ctx_new + hssl_ctx_t ssl_ctx = NULL; + if (io->ssl_ctx) { + ssl_ctx = io->ssl_ctx; + } else if (g_ssl_ctx) { + ssl_ctx = g_ssl_ctx; + } else { + io->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); + io->alloced_ssl_ctx = 1; + } + if (ssl_ctx == NULL) { + io->error = ERR_NEW_SSL_CTX; + goto connect_error; + } + hssl_t ssl = hssl_new(ssl_ctx, io->fd); + if (ssl == NULL) { + io->error = ERR_NEW_SSL; + goto connect_error; + } + io->ssl = ssl; + } + if (io->hostname) { + hssl_set_sni_hostname(io->ssl, io->hostname); + } + ssl_client_handshake(io); + } + else { + // NOTE: SSL call connect_cb after handshake finished + __connect_cb(io); + } + + return; + } + +connect_error: + hlogw("connfd=%d connect error: %s:%d", io->fd, socket_strerror(io->error), io->error); + hio_close(io); +} + +static void nio_connect_event_cb(hevent_t* ev) { + hio_t* io = (hio_t*)ev->userdata; + uint32_t id = (uintptr_t)ev->privdata; + if (io->id != id) return; + nio_connect(io); +} + +static int nio_connect_async(hio_t* io) { + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.cb = nio_connect_event_cb; + ev.userdata = io; + ev.privdata = (void*)(uintptr_t)io->id; + hloop_post_event(io->loop, &ev); + return 0; +} + +static int __nio_read(hio_t* io, void* buf, int len) { + int nread = 0; + switch (io->io_type) { + case HIO_TYPE_SSL: + nread = hssl_read(io->ssl, buf, len); + break; + case HIO_TYPE_TCP: + nread = recv(io->fd, buf, len, 0); + break; + case HIO_TYPE_UDP: + case HIO_TYPE_KCP: + case HIO_TYPE_IP: + { + socklen_t addrlen = sizeof(sockaddr_u); + nread = recvfrom(io->fd, buf, len, 0, io->peeraddr, &addrlen); + } + break; + default: + nread = read(io->fd, buf, len); + break; + } + // hlogd("read retval=%d", nread); + return nread; +} + +static int __nio_write(hio_t* io, const void* buf, int len) { + int nwrite = 0; + switch (io->io_type) { + case HIO_TYPE_SSL: + nwrite = hssl_write(io->ssl, buf, len); + break; + case HIO_TYPE_TCP: + { + int flag = 0; +#ifdef MSG_NOSIGNAL + flag |= MSG_NOSIGNAL; +#endif + nwrite = send(io->fd, buf, len, flag); + } + break; + case HIO_TYPE_UDP: + case HIO_TYPE_KCP: + case HIO_TYPE_IP: + nwrite = sendto(io->fd, buf, len, 0, io->peeraddr, SOCKADDR_LEN(io->peeraddr)); + break; + default: + nwrite = write(io->fd, buf, len); + break; + } + // hlogd("write retval=%d", nwrite); + return nwrite; +} + +static void nio_read(hio_t* io) { + // printd("nio_read fd=%d\n", io->fd); + void* buf; + int len = 0, nread = 0, err = 0; +read: + buf = io->readbuf.base + io->readbuf.tail; + if (io->read_flags & HIO_READ_UNTIL_LENGTH) { + len = io->read_until_length - (io->readbuf.tail - io->readbuf.head); + } else { + len = io->readbuf.len - io->readbuf.tail; + } + assert(len > 0); + nread = __nio_read(io, buf, len); + // printd("read retval=%d\n", nread); + if (nread < 0) { + err = socket_errno(); + if (err == EAGAIN || err == EINTR) { + // goto read_done; + return; + } else if (err == EMSGSIZE) { + // ignore + return; + } else { + // perror("read"); + io->error = err; + goto read_error; + } + } + if (nread == 0) { + goto disconnect; + } + io->readbuf.tail += nread; + __read_cb(io, buf, nread); + if (nread == len && !io->closed) { + // NOTE: ssl may have own cache + if (io->io_type == HIO_TYPE_SSL) { + // read continue + goto read; + } + } + return; +read_error: +disconnect: + if (io->io_type & HIO_TYPE_SOCK_STREAM) { + hio_close(io); + } +} + +static void nio_write(hio_t* io) { + // printd("nio_write fd=%d\n", io->fd); + int nwrite = 0, err = 0; + hrecursive_mutex_lock(&io->write_mutex); +write: + if (write_queue_empty(&io->write_queue)) { + hrecursive_mutex_unlock(&io->write_mutex); + if (io->close) { + io->close = 0; + hio_close(io); + } + return; + } + offset_buf_t* pbuf = write_queue_front(&io->write_queue); + char* base = pbuf->base; + char* buf = base + pbuf->offset; + int len = pbuf->len - pbuf->offset; + nwrite = __nio_write(io, buf, len); + // printd("write retval=%d\n", nwrite); + if (nwrite < 0) { + err = socket_errno(); + if (err == EAGAIN || err == EINTR) { + hrecursive_mutex_unlock(&io->write_mutex); + return; + } else { + // perror("write"); + io->error = err; + goto write_error; + } + } + if (nwrite == 0) { + goto disconnect; + } + pbuf->offset += nwrite; + io->write_bufsize -= nwrite; + __write_cb(io, buf, nwrite); + if (nwrite == len) { + // NOTE: after write_cb, pbuf maybe invalid. + // HV_FREE(pbuf->base); + HV_FREE(base); + write_queue_pop_front(&io->write_queue); + if (!io->closed) { + // write continue + goto write; + } + } + hrecursive_mutex_unlock(&io->write_mutex); + return; +write_error: +disconnect: + hrecursive_mutex_unlock(&io->write_mutex); + if (io->io_type & HIO_TYPE_SOCK_STREAM) { + hio_close(io); + } +} + +static void hio_handle_events(hio_t* io) { + if ((io->events & HV_READ) && (io->revents & HV_READ)) { + if (io->accept) { + nio_accept(io); + } + else { + nio_read(io); + } + } + + if ((io->events & HV_WRITE) && (io->revents & HV_WRITE)) { + // NOTE: del HV_WRITE, if write_queue empty + hrecursive_mutex_lock(&io->write_mutex); + if (write_queue_empty(&io->write_queue)) { + hio_del(io, HV_WRITE); + } + hrecursive_mutex_unlock(&io->write_mutex); + if (io->connect) { + // NOTE: connect just do once + // ONESHOT + io->connect = 0; + + nio_connect(io); + } + else { + nio_write(io); + } + } + + io->revents = 0; +} + +int hio_accept(hio_t* io) { + io->accept = 1; + return hio_add(io, hio_handle_events, HV_READ); +} + +int hio_connect(hio_t* io) { + int ret = connect(io->fd, io->peeraddr, SOCKADDR_LEN(io->peeraddr)); +#ifdef OS_WIN + if (ret < 0 && socket_errno() != WSAEWOULDBLOCK) { +#else + if (ret < 0 && socket_errno() != EINPROGRESS) { +#endif + perror("connect"); + io->error = socket_errno(); + hio_close_async(io); + return ret; + } + if (ret == 0) { + // connect ok + nio_connect_async(io); + return 0; + } + int timeout = io->connect_timeout ? io->connect_timeout : HIO_DEFAULT_CONNECT_TIMEOUT; + io->connect_timer = htimer_add(io->loop, __connect_timeout_cb, timeout, 1); + io->connect_timer->privdata = io; + io->connect = 1; + return hio_add(io, hio_handle_events, HV_WRITE); +} + +int hio_read (hio_t* io) { + if (io->closed) { + hloge("hio_read called but fd[%d] already closed!", io->fd); + return -1; + } + hio_add(io, hio_handle_events, HV_READ); + if (io->readbuf.tail > io->readbuf.head && + io->unpack_setting == NULL && + io->read_flags == 0) { + hio_read_remain(io); + } + return 0; +} + +int hio_write (hio_t* io, const void* buf, size_t len) { + if (io->closed) { + hloge("hio_write called but fd[%d] already closed!", io->fd); + return -1; + } + int nwrite = 0, err = 0; + hrecursive_mutex_lock(&io->write_mutex); +#if WITH_KCP + if (io->io_type == HIO_TYPE_KCP) { + nwrite = hio_write_kcp(io, buf, len); + // if (nwrite < 0) goto write_error; + goto write_done; + } +#endif + if (write_queue_empty(&io->write_queue)) { +try_write: + nwrite = __nio_write(io, buf, len); + // printd("write retval=%d\n", nwrite); + if (nwrite < 0) { + err = socket_errno(); + if (err == EAGAIN || err == EINTR) { + nwrite = 0; + hlogw("try_write failed, enqueue!"); + goto enqueue; + } else { + // perror("write"); + io->error = err; + goto write_error; + } + } + if (nwrite == 0) { + goto disconnect; + } + if (nwrite == len) { + goto write_done; + } +enqueue: + hio_add(io, hio_handle_events, HV_WRITE); + } + if (nwrite < len) { + if (io->write_bufsize + len - nwrite > io->max_write_bufsize) { + hloge("write bufsize > %u, close it!", io->max_write_bufsize); + io->error = ERR_OVER_LIMIT; + goto write_error; + } + offset_buf_t remain; + remain.len = len - nwrite; + remain.offset = 0; + // NOTE: free in nio_write + HV_ALLOC(remain.base, remain.len); + memcpy(remain.base, ((char*)buf) + nwrite, remain.len); + if (io->write_queue.maxsize == 0) { + write_queue_init(&io->write_queue, 4); + } + write_queue_push_back(&io->write_queue, &remain); + io->write_bufsize += remain.len; + if (io->write_bufsize > WRITE_BUFSIZE_HIGH_WATER) { + hlogw("write len=%u enqueue %u, bufsize=%u over high water %u", + (unsigned int)len, + (unsigned int)(remain.len - remain.offset), + (unsigned int)io->write_bufsize, + (unsigned int)WRITE_BUFSIZE_HIGH_WATER); + } + } +write_done: + hrecursive_mutex_unlock(&io->write_mutex); + if (nwrite > 0) { + __write_cb(io, buf, nwrite); + } + return nwrite; +write_error: +disconnect: + hrecursive_mutex_unlock(&io->write_mutex); + /* NOTE: + * We usually free resources in hclose_cb, + * if hio_close_sync, we have to be very careful to avoid using freed resources. + * But if hio_close_async, we do not have to worry about this. + */ + if (io->io_type & HIO_TYPE_SOCK_STREAM) { + hio_close_async(io); + } + return nwrite < 0 ? nwrite : -1; +} + +int hio_close (hio_t* io) { + if (io->closed) return 0; + if (hv_gettid() != io->loop->tid) { + return hio_close_async(io); + } + + hrecursive_mutex_lock(&io->write_mutex); + if (io->closed) { + hrecursive_mutex_unlock(&io->write_mutex); + return 0; + } + if (!write_queue_empty(&io->write_queue) && io->error == 0 && io->close == 0) { + io->close = 1; + hrecursive_mutex_unlock(&io->write_mutex); + hlogw("write_queue not empty, close later."); + int timeout_ms = io->close_timeout ? io->close_timeout : HIO_DEFAULT_CLOSE_TIMEOUT; + io->close_timer = htimer_add(io->loop, __close_timeout_cb, timeout_ms, 1); + io->close_timer->privdata = io; + return 0; + } + io->closed = 1; + hrecursive_mutex_unlock(&io->write_mutex); + + hio_done(io); + __close_cb(io); + if (io->ssl) { + hssl_free(io->ssl); + io->ssl = NULL; + } + if (io->ssl_ctx && io->alloced_ssl_ctx) { + hssl_ctx_free(io->ssl_ctx); + io->ssl_ctx = NULL; + } + SAFE_FREE(io->hostname); + if (io->io_type & HIO_TYPE_SOCKET) { + closesocket(io->fd); + } + return 0; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/nlog.c b/external/libhv/libhv-1.3.2/event/nlog.c new file mode 100644 index 0000000..fb8ac45 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/nlog.c @@ -0,0 +1,87 @@ +#include "nlog.h" + +#include "list.h" +#include "hdef.h" +#include "hbase.h" +#include "hsocket.h" +#include "hmutex.h" + +typedef struct network_logger_s { + hloop_t* loop; + hio_t* listenio; + struct list_head clients; +} network_logger_t; + +typedef struct nlog_client { + hio_t* io; + struct list_node node; +} nlog_client; + +static network_logger_t s_logger = {0}; +static hmutex_t s_mutex; + +static void on_close(hio_t* io) { + printd("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + + nlog_client* client = (nlog_client*)hevent_userdata(io); + if (client) { + hevent_set_userdata(io, NULL); + + hmutex_lock(&s_mutex); + list_del(&client->node); + hmutex_unlock(&s_mutex); + + HV_FREE(client); + } +} + +static void on_read(hio_t* io, void* buf, int readbytes) { + printd("on_read fd=%d readbytes=%d\n", hio_fd(io), readbytes); + printd("< %s\n", (char*)buf); + // nothing to do +} + +static void on_accept(hio_t* io) { + /* + printd("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + hio_setcb_read(io, on_read); + hio_setcb_close(io, on_close); + hio_read(io); + + // free on_close + nlog_client* client; + HV_ALLOC_SIZEOF(client); + client->io = io; + hevent_set_userdata(io, client); + + hmutex_lock(&s_mutex); + list_add(&client->node, &s_logger.clients); + hmutex_unlock(&s_mutex); +} + +void network_logger(int loglevel, const char* buf, int len) { + struct list_node* node; + nlog_client* client; + + hmutex_lock(&s_mutex); + list_for_each (node, &s_logger.clients) { + client = list_entry(node, nlog_client, node); + hio_write(client->io, buf, len); + } + hmutex_unlock(&s_mutex); +} + +hio_t* nlog_listen(hloop_t* loop, int port) { + s_logger.loop = loop; + s_logger.listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); + list_init(&s_logger.clients); + hmutex_init(&s_mutex); + return s_logger.listenio; +} diff --git a/external/libhv/libhv-1.3.2/event/nlog.h b/external/libhv/libhv-1.3.2/event/nlog.h new file mode 100644 index 0000000..568cbbd --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/nlog.h @@ -0,0 +1,44 @@ +#ifndef HV_NLOG_H_ +#define HV_NLOG_H_ + +// nlog: extend hlog use hloop + +/* you can recv log by: + * Windows: telnet ip port + * Linux: nc ip port + */ + +/* + * @see examples/hloop_test.c +#include "hlog.h" +#include "nlog.h" + +void timer_write_log(htimer_t* timer) { + static int cnt = 0; + hlogi("[%d] Do you recv me?", ++cnt); +} + +int main() { + hloop_t* loop = hloop_new(0); + hlog_set_handler(network_logger); + nlog_listen(loop, DEFAULT_LOG_PORT); + htimer_add(loop, timer_write_log, 1000, INFINITE); + hloop_run(loop); + hloop_free(&loop); +} + */ + + +#include "hexport.h" +#include "hloop.h" + +#define DEFAULT_LOG_PORT 10514 + +BEGIN_EXTERN_C + +HV_EXPORT void network_logger(int loglevel, const char* buf, int len); +HV_EXPORT hio_t* nlog_listen(hloop_t* loop, int port); + +END_EXTERN_C + +#endif // HV_NLOG_H_ diff --git a/external/libhv/libhv-1.3.2/event/noevent.c b/external/libhv/libhv-1.3.2/event/noevent.c new file mode 100644 index 0000000..a03eecd --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/noevent.c @@ -0,0 +1,25 @@ +#include "iowatcher.h" + +#ifdef EVENT_NOEVENT +int iowatcher_init(hloop_t* loop) { + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + hv_delay(timeout); + return 0; +} + +#endif diff --git a/external/libhv/libhv-1.3.2/event/overlapio.c b/external/libhv/libhv-1.3.2/event/overlapio.c new file mode 100644 index 0000000..4fe2cb6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/overlapio.c @@ -0,0 +1,419 @@ +// WARN: overlapio maybe need MemoryPool to avoid alloc/free +#include "iowatcher.h" + +#ifdef EVENT_IOCP +#include "overlapio.h" +#include "hevent.h" + +#define ACCEPTEX_NUM 10 + +int post_acceptex(hio_t* listenio, hoverlapped_t* hovlp) { + LPFN_ACCEPTEX AcceptEx = NULL; + GUID guidAcceptEx = WSAID_ACCEPTEX; + DWORD dwbytes = 0; + if (WSAIoctl(listenio->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, + &guidAcceptEx, sizeof(guidAcceptEx), + &AcceptEx, sizeof(AcceptEx), + &dwbytes, NULL, NULL) != 0) { + return WSAGetLastError(); + } + int connfd = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED); + if (connfd < 0) { + return WSAGetLastError(); + } + if (hovlp == NULL) { + HV_ALLOC_SIZEOF(hovlp); + hovlp->buf.len = 20 + sizeof(struct sockaddr_in6) * 2; + HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); + } + hovlp->fd = connfd; + hovlp->event = HV_READ; + hovlp->io = listenio; + if (AcceptEx(listenio->fd, connfd, hovlp->buf.buf, 0, sizeof(struct sockaddr_in6), sizeof(struct sockaddr_in6), + &dwbytes, &hovlp->ovlp) != TRUE) { + int err = WSAGetLastError(); + if (err != ERROR_IO_PENDING) { + fprintf(stderr, "AcceptEx error: %d\n", err); + return err; + } + } + return 0; +} + +int post_recv(hio_t* io, hoverlapped_t* hovlp) { + if (hovlp == NULL) { + HV_ALLOC_SIZEOF(hovlp); + } + hovlp->fd = io->fd; + hovlp->event = HV_READ; + hovlp->io = io; + hovlp->buf.len = io->readbuf.len; + if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { + HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); + } + else { + hovlp->buf.buf = io->readbuf.base; + } + //memset(hovlp->buf.buf, 0, hovlp->buf.len); + DWORD dwbytes = 0; + DWORD flags = 0; + int ret = 0; + if (io->io_type == HIO_TYPE_TCP) { + ret = WSARecv(io->fd, &hovlp->buf, 1, &dwbytes, &flags, &hovlp->ovlp, NULL); + } + else if (io->io_type == HIO_TYPE_UDP || + io->io_type == HIO_TYPE_IP) { + if (hovlp->addr == NULL) { + hovlp->addrlen = sizeof(struct sockaddr_in6); + HV_ALLOC(hovlp->addr, sizeof(struct sockaddr_in6)); + } + ret = WSARecvFrom(io->fd, &hovlp->buf, 1, &dwbytes, &flags, hovlp->addr, &hovlp->addrlen, &hovlp->ovlp, NULL); + } + else { + ret = -1; + } + //printd("WSARecv ret=%d bytes=%u\n", ret, dwbytes); + if (ret != 0) { + int err = WSAGetLastError(); + if (err != ERROR_IO_PENDING) { + fprintf(stderr, "WSARecv error: %d\n", err); + return err; + } + } + return 0; +} + +static void on_acceptex_complete(hio_t* io) { + printd("on_acceptex_complete------\n"); + hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; + int listenfd = io->fd; + int connfd = hovlp->fd; + LPFN_GETACCEPTEXSOCKADDRS GetAcceptExSockaddrs = NULL; + GUID guidGetAcceptExSockaddrs = WSAID_GETACCEPTEXSOCKADDRS; + DWORD dwbytes = 0; + if (WSAIoctl(connfd, SIO_GET_EXTENSION_FUNCTION_POINTER, + &guidGetAcceptExSockaddrs, sizeof(guidGetAcceptExSockaddrs), + &GetAcceptExSockaddrs, sizeof(GetAcceptExSockaddrs), + &dwbytes, NULL, NULL) != 0) { + return; + } + struct sockaddr* plocaladdr = NULL; + struct sockaddr* ppeeraddr = NULL; + socklen_t localaddrlen; + socklen_t peeraddrlen; + GetAcceptExSockaddrs(hovlp->buf.buf, 0, sizeof(struct sockaddr_in6), sizeof(struct sockaddr_in6), + &plocaladdr, &localaddrlen, &ppeeraddr, &peeraddrlen); + memcpy(io->localaddr, plocaladdr, localaddrlen); + memcpy(io->peeraddr, ppeeraddr, peeraddrlen); + if (io->accept_cb) { + setsockopt(connfd, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, (const char*)&listenfd, sizeof(int)); + hio_t* connio = hio_get(io->loop, connfd); + connio->userdata = io->userdata; + memcpy(connio->localaddr, io->localaddr, localaddrlen); + memcpy(connio->peeraddr, io->peeraddr, peeraddrlen); + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("accept listenfd=%d connfd=%d [%s] <= [%s]\n", listenfd, connfd, + SOCKADDR_STR(connio->localaddr, localaddrstr), + SOCKADDR_STR(connio->peeraddr, peeraddrstr)); + */ + //printd("accept_cb------\n"); + io->accept_cb(connio); + //printd("accept_cb======\n"); + } + post_acceptex(io, hovlp); +} + +static void on_connectex_complete(hio_t* io) { + printd("on_connectex_complete------\n"); + hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; + io->error = hovlp->error; + HV_FREE(io->hovlp); + if (io->error != 0) { + hio_close(io); + return; + } + if (io->connect_cb) { + setsockopt(io->fd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0); + socklen_t addrlen = sizeof(struct sockaddr_in6); + getsockname(io->fd, io->localaddr, &addrlen); + addrlen = sizeof(struct sockaddr_in6); + getpeername(io->fd, io->peeraddr, &addrlen); + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("connect connfd=%d [%s] => [%s]\n", io->fd, + SOCKADDR_STR(io->localaddr, localaddrstr), + SOCKADDR_STR(io->peeraddr, peeraddrstr)); + */ + //printd("connect_cb------\n"); + io->connect_cb(io); + //printd("connect_cb======\n"); + } +} + +static void on_wsarecv_complete(hio_t* io) { + printd("on_recv_complete------\n"); + hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; + if (hovlp->bytes == 0) { + io->error = WSAGetLastError(); + hio_close(io); + return; + } + + if (io->read_cb) { + if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { + if (hovlp->addr && hovlp->addrlen) { + hio_set_peeraddr(io, hovlp->addr, hovlp->addrlen); + } + } + //printd("read_cb------\n"); + io->read_cb(io, hovlp->buf.buf, hovlp->bytes); + //printd("read_cb======\n"); + } + + if (io->io_type == HIO_TYPE_TCP) { + // reuse hovlp + if (!io->closed) { + post_recv(io, hovlp); + } + } + else if (io->io_type == HIO_TYPE_UDP || + io->io_type == HIO_TYPE_IP) { + HV_FREE(hovlp->buf.buf); + HV_FREE(hovlp->addr); + HV_FREE(io->hovlp); + } +} + +static void on_wsasend_complete(hio_t* io) { + printd("on_send_complete------\n"); + hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; + if (hovlp->bytes == 0) { + io->error = WSAGetLastError(); + hio_close(io); + goto end; + } + if (io->write_cb) { + if (io->io_type == HIO_TYPE_UDP || io->io_type == HIO_TYPE_IP) { + if (hovlp->addr) { + hio_set_peeraddr(io, hovlp->addr, hovlp->addrlen); + } + } + //printd("write_cb------\n"); + io->write_cb(io, hovlp->buf.buf, hovlp->bytes); + //printd("write_cb======\n"); + } +end: + if (io->hovlp) { + HV_FREE(hovlp->buf.buf); + HV_FREE(io->hovlp); + } +} + +static void hio_handle_events(hio_t* io) { + if ((io->events & HV_READ) && (io->revents & HV_READ)) { + if (io->accept) { + on_acceptex_complete(io); + } + else { + on_wsarecv_complete(io); + } + } + + if ((io->events & HV_WRITE) && (io->revents & HV_WRITE)) { + // NOTE: HV_WRITE just do once + // ONESHOT + iowatcher_del_event(io->loop, io->fd, HV_WRITE); + io->events &= ~HV_WRITE; + if (io->connect) { + io->connect = 0; + + on_connectex_complete(io); + } + else { + on_wsasend_complete(io); + } + } + + io->revents = 0; +} + +int hio_accept (hio_t* io) { + for (int i = 0; i < ACCEPTEX_NUM; ++i) { + post_acceptex(io, NULL); + } + io->accept = 1; + return hio_add(io, hio_handle_events, HV_READ); +} + +int hio_connect (hio_t* io) { + // NOTE: ConnectEx must call bind + struct sockaddr_in localaddr; + socklen_t addrlen = sizeof(localaddr); + memset(&localaddr, 0, addrlen); + localaddr.sin_family = AF_INET; + localaddr.sin_addr.s_addr = htonl(INADDR_ANY); + localaddr.sin_port = htons(0); + if (bind(io->fd, (struct sockaddr*)&localaddr, addrlen) < 0) { + perror("bind"); + goto error; + } + // ConnectEx + io->connectex = 1; + LPFN_CONNECTEX ConnectEx = NULL; + GUID guidConnectEx = WSAID_CONNECTEX; + DWORD dwbytes; + if (WSAIoctl(io->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, + &guidConnectEx, sizeof(guidConnectEx), + &ConnectEx, sizeof(ConnectEx), + &dwbytes, NULL, NULL) != 0) { + goto error; + } + // NOTE: free on_connectex_complete + hoverlapped_t* hovlp; + HV_ALLOC_SIZEOF(hovlp); + hovlp->fd = io->fd; + hovlp->event = HV_WRITE; + hovlp->io = io; + if (ConnectEx(io->fd, io->peeraddr, sizeof(struct sockaddr_in6), NULL, 0, &dwbytes, &hovlp->ovlp) != TRUE) { + int err = WSAGetLastError(); + if (err != ERROR_IO_PENDING) { + fprintf(stderr, "AcceptEx error: %d\n", err); + goto error; + } + } + io->connect = 1; + return hio_add(io, hio_handle_events, HV_WRITE); +error: + hio_close(io); + return 0; +} + +int hio_read (hio_t* io) { + post_recv(io, NULL); + return hio_add(io, hio_handle_events, HV_READ); +} + +int hio_write(hio_t* io, const void* buf, size_t len) { + int nwrite = 0; +try_send: + if (io->io_type == HIO_TYPE_TCP) { + nwrite = send(io->fd, buf, len, 0); + } + else if (io->io_type == HIO_TYPE_UDP) { + nwrite = sendto(io->fd, buf, len, 0, io->peeraddr, sizeof(struct sockaddr_in6)); + } + else if (io->io_type == HIO_TYPE_IP) { + goto WSASend; + } + else { + nwrite = -1; + } + //printd("write retval=%d\n", nwrite); + if (nwrite < 0) { + if (socket_errno() == EAGAIN) { + nwrite = 0; + goto WSASend; + } + else { + perror("write"); + io->error = socket_errno(); + goto write_error; + } + } + if (nwrite == 0) { + goto disconnect; + } + if (io->write_cb) { + //printd("try_write_cb------\n"); + io->write_cb(io, buf, nwrite); + //printd("try_write_cb======\n"); + } + if (nwrite == len) { + //goto write_done; + return nwrite; + } +WSASend: + { + hoverlapped_t* hovlp; + HV_ALLOC_SIZEOF(hovlp); + hovlp->fd = io->fd; + hovlp->event = HV_WRITE; + hovlp->buf.len = len - nwrite; + // NOTE: free on_send_complete + HV_ALLOC(hovlp->buf.buf, hovlp->buf.len); + memcpy(hovlp->buf.buf, ((char*)buf) + nwrite, hovlp->buf.len); + hovlp->io = io; + DWORD dwbytes = 0; + DWORD flags = 0; + int ret = 0; + if (io->io_type == HIO_TYPE_TCP) { + ret = WSASend(io->fd, &hovlp->buf, 1, &dwbytes, flags, &hovlp->ovlp, NULL); + } + else if (io->io_type == HIO_TYPE_UDP || + io->io_type == HIO_TYPE_IP) { + ret = WSASendTo(io->fd, &hovlp->buf, 1, &dwbytes, flags, io->peeraddr, sizeof(struct sockaddr_in6), &hovlp->ovlp, NULL); + } + else { + ret = -1; + } + //printd("WSASend ret=%d bytes=%u\n", ret, dwbytes); + if (ret != 0) { + int err = WSAGetLastError(); + if (err != ERROR_IO_PENDING) { + fprintf(stderr, "WSASend error: %d\n", err); + return ret; + } + } + return hio_add(io, hio_handle_events, HV_WRITE); + } +write_error: +disconnect: + hio_close(io); + return 0; +} + +int hio_close (hio_t* io) { + if (io->closed) return 0; + io->closed = 1; + hio_done(io); + if (io->hovlp) { + hoverlapped_t* hovlp = (hoverlapped_t*)io->hovlp; + // NOTE: hread buf provided by caller + if (hovlp->buf.buf != io->readbuf.base) { + HV_FREE(hovlp->buf.buf); + } + HV_FREE(hovlp->addr); + HV_FREE(io->hovlp); + } + if (io->close_cb) { + //printd("close_cb------\n"); + io->close_cb(io); + //printd("close_cb======\n"); + } + if (io->io_type & HIO_TYPE_SOCKET) { +#ifdef USE_DISCONNECTEX + // DisconnectEx reuse socket + if (io->connectex) { + io->connectex = 0; + LPFN_DISCONNECTEX DisconnectEx = NULL; + GUID guidDisconnectEx = WSAID_DISCONNECTEX; + DWORD dwbytes; + if (WSAIoctl(io->fd, SIO_GET_EXTENSION_FUNCTION_POINTER, + &guidDisconnectEx, sizeof(guidDisconnectEx), + &DisconnectEx, sizeof(DisconnectEx), + &dwbytes, NULL, NULL) != 0) { + return; + } + DisconnectEx(io->fd, NULL, 0, 0); + } +#else + closesocket(io->fd); +#endif + } + return 0; +} + +#endif diff --git a/external/libhv/libhv-1.3.2/event/overlapio.h b/external/libhv/libhv-1.3.2/event/overlapio.h new file mode 100644 index 0000000..69fb026 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/overlapio.h @@ -0,0 +1,33 @@ +#ifndef HV_OVERLAPPED_H_ +#define HV_OVERLAPPED_H_ + +#include "iowatcher.h" + +#ifdef EVENT_IOCP + +#include "hbuf.h" +#include "hsocket.h" +#include +#ifdef _MSC_VER +#pragma comment(lib, "mswsock.lib") +#endif + +typedef struct hoverlapped_s { + OVERLAPPED ovlp; + int fd; + int event; + WSABUF buf; + int bytes; + int error; + hio_t* io; + // for recvfrom + struct sockaddr* addr; + int addrlen; +} hoverlapped_t; + +int post_acceptex(hio_t* listenio, hoverlapped_t* hovlp); +int post_recv(hio_t* io, hoverlapped_t* hovlp); + +#endif + +#endif // HV_OVERLAPPED_H_ diff --git a/external/libhv/libhv-1.3.2/event/poll.c b/external/libhv/libhv-1.3.2/event/poll.c new file mode 100644 index 0000000..4c1073b --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/poll.c @@ -0,0 +1,135 @@ +#include "iowatcher.h" + +#ifdef EVENT_POLL +#include "hplatform.h" +#include "hdef.h" +#include "hevent.h" + +#ifdef OS_WIN +#define poll WSAPoll +#endif + +#ifdef OS_LINUX +#include +#endif + +#include "array.h" +#define FDS_INIT_SIZE 64 +ARRAY_DECL(struct pollfd, pollfds); + +typedef struct poll_ctx_s { + int capacity; + struct pollfds fds; +} poll_ctx_t; + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + poll_ctx_t* poll_ctx; + HV_ALLOC_SIZEOF(poll_ctx); + pollfds_init(&poll_ctx->fds, FDS_INIT_SIZE); + loop->iowatcher = poll_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + if (loop->iowatcher == NULL) return 0; + poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; + pollfds_cleanup(&poll_ctx->fds); + HV_FREE(loop->iowatcher); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; + hio_t* io = loop->ios.ptr[fd]; + int idx = io->event_index[0]; + struct pollfd* pfd = NULL; + if (idx < 0) { + io->event_index[0] = idx = poll_ctx->fds.size; + if (idx == poll_ctx->fds.maxsize) { + pollfds_double_resize(&poll_ctx->fds); + } + poll_ctx->fds.size++; + pfd = poll_ctx->fds.ptr + idx; + pfd->fd = fd; + pfd->events = 0; + pfd->revents = 0; + } + else { + pfd = poll_ctx->fds.ptr + idx; + assert(pfd->fd == fd); + } + if (events & HV_READ) { + pfd->events |= POLLIN; + } + if (events & HV_WRITE) { + pfd->events |= POLLOUT; + } + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; + if (poll_ctx == NULL) return 0; + hio_t* io = loop->ios.ptr[fd]; + + int idx = io->event_index[0]; + if (idx < 0) return 0; + struct pollfd* pfd = poll_ctx->fds.ptr + idx; + assert(pfd->fd == fd); + if (events & HV_READ) { + pfd->events &= ~POLLIN; + } + if (events & HV_WRITE) { + pfd->events &= ~POLLOUT; + } + if (pfd->events == 0) { + pollfds_del_nomove(&poll_ctx->fds, idx); + // NOTE: correct event_index + if (idx < poll_ctx->fds.size) { + hio_t* last = loop->ios.ptr[poll_ctx->fds.ptr[idx].fd]; + last->event_index[0] = idx; + } + io->event_index[0] = -1; + } + return 0; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + poll_ctx_t* poll_ctx = (poll_ctx_t*)loop->iowatcher; + if (poll_ctx == NULL) return 0; + if (poll_ctx->fds.size == 0) return 0; + int npoll = poll(poll_ctx->fds.ptr, poll_ctx->fds.size, timeout); + if (npoll < 0) { + if (errno == EINTR) { + return 0; + } + perror("poll"); + return npoll; + } + if (npoll == 0) return 0; + int nevents = 0; + for (int i = 0; i < poll_ctx->fds.size; ++i) { + int fd = poll_ctx->fds.ptr[i].fd; + short revents = poll_ctx->fds.ptr[i].revents; + if (revents) { + ++nevents; + hio_t* io = loop->ios.ptr[fd]; + if (io) { + if (revents & (POLLIN | POLLHUP | POLLERR)) { + io->revents |= HV_READ; + } + if (revents & (POLLOUT | POLLHUP | POLLERR)) { + io->revents |= HV_WRITE; + } + EVENT_PENDING(io); + } + } + if (nevents == npoll) break; + } + return nevents; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/rudp.c b/external/libhv/libhv-1.3.2/event/rudp.c new file mode 100644 index 0000000..2a3df23 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/rudp.c @@ -0,0 +1,167 @@ +#include "rudp.h" + +#if WITH_RUDP + +#include "hevent.h" + +void rudp_entry_free(rudp_entry_t* entry) { +#if WITH_KCP + kcp_release(&entry->kcp); +#endif + HV_FREE(entry); +} + +void rudp_init(rudp_t* rudp) { + // printf("rudp init\n"); + rudp->rb_root.rb_node = NULL; + hmutex_init(&rudp->mutex); +} + +void rudp_cleanup(rudp_t* rudp) { + // printf("rudp cleaup\n"); + struct rb_node* n = NULL; + rudp_entry_t* e = NULL; + while ((n = rudp->rb_root.rb_node)) { + e = rb_entry(n, rudp_entry_t, rb_node); + rb_erase(n, &rudp->rb_root); + rudp_entry_free(e); + } + hmutex_destroy(&rudp->mutex); +} + +bool rudp_insert(rudp_t* rudp, rudp_entry_t* entry) { + struct rb_node** n = &rudp->rb_root.rb_node; + struct rb_node* parent = NULL; + rudp_entry_t* e = NULL; + int cmp = 0; + bool exists = false; + while (*n) { + parent = *n; + e = rb_entry(*n, rudp_entry_t, rb_node); + cmp = memcmp(&entry->addr, &e->addr, sizeof(sockaddr_u)); + if (cmp < 0) { + n = &(*n)->rb_left; + } else if (cmp > 0) { + n = &(*n)->rb_right; + } else { + exists = true; + break; + } + } + + if (!exists) { + rb_link_node(&entry->rb_node, parent, n); + rb_insert_color(&entry->rb_node, &rudp->rb_root); + } + return !exists; +} + +rudp_entry_t* rudp_search(rudp_t* rudp, struct sockaddr* addr) { + struct rb_node* n = rudp->rb_root.rb_node; + rudp_entry_t* e = NULL; + int cmp = 0; + bool exists = false; + while (n) { + e = rb_entry(n, rudp_entry_t, rb_node); + cmp = memcmp(addr, &e->addr, sizeof(sockaddr_u)); + if (cmp < 0) { + n = n->rb_left; + } else if (cmp > 0) { + n = n->rb_right; + } else { + exists = true; + break; + } + } + return exists ? e : NULL; +} + +rudp_entry_t* rudp_remove(rudp_t* rudp, struct sockaddr* addr) { + hmutex_lock(&rudp->mutex); + rudp_entry_t* e = rudp_search(rudp, addr); + if (e) { + // printf("rudp_remove "); + // SOCKADDR_PRINT(addr); + rb_erase(&e->rb_node, &rudp->rb_root); + } + hmutex_unlock(&rudp->mutex); + return e; +} + +rudp_entry_t* rudp_get(rudp_t* rudp, struct sockaddr* addr) { + hmutex_lock(&rudp->mutex); + struct rb_node** n = &rudp->rb_root.rb_node; + struct rb_node* parent = NULL; + rudp_entry_t* e = NULL; + int cmp = 0; + bool exists = false; + // search + while (*n) { + parent = *n; + e = rb_entry(*n, rudp_entry_t, rb_node); + cmp = memcmp(addr, &e->addr, sizeof(sockaddr_u)); + if (cmp < 0) { + n = &(*n)->rb_left; + } else if (cmp > 0) { + n = &(*n)->rb_right; + } else { + exists = true; + break; + } + } + + if (!exists) { + // insert + // printf("rudp_insert "); + // SOCKADDR_PRINT(addr); + HV_ALLOC_SIZEOF(e); + memcpy(&e->addr, addr, SOCKADDR_LEN(addr)); + rb_link_node(&e->rb_node, parent, n); + rb_insert_color(&e->rb_node, &rudp->rb_root); + } + hmutex_unlock(&rudp->mutex); + return e; +} + +void rudp_del(rudp_t* rudp, struct sockaddr* addr) { + hmutex_lock(&rudp->mutex); + rudp_entry_t* e = rudp_search(rudp, addr); + if (e) { + // printf("rudp_remove "); + // SOCKADDR_PRINT(addr); + rb_erase(&e->rb_node, &rudp->rb_root); + rudp_entry_free(e); + } + hmutex_unlock(&rudp->mutex); +} + +rudp_entry_t* hio_get_rudp(hio_t* io) { + rudp_entry_t* rudp = rudp_get(&io->rudp, io->peeraddr); + rudp->io = io; + return rudp; +} + +static void hio_close_rudp_event_cb(hevent_t* ev) { + rudp_entry_t* entry = (rudp_entry_t*)ev->userdata; + rudp_del(&entry->io->rudp, (struct sockaddr*)&entry->addr); + // rudp_entry_free(entry); +} + +int hio_close_rudp(hio_t* io, struct sockaddr* peeraddr) { + if (peeraddr == NULL) peeraddr = io->peeraddr; + // NOTE: do rudp_del for thread-safe + rudp_entry_t* entry = rudp_get(&io->rudp, peeraddr); + // NOTE: just rudp_remove first, do rudp_entry_free async for safe. + // rudp_entry_t* entry = rudp_remove(&io->rudp, peeraddr); + if (entry) { + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.cb = hio_close_rudp_event_cb; + ev.userdata = entry; + ev.priority = HEVENT_HIGH_PRIORITY; + hloop_post_event(io->loop, &ev); + } + return 0; +} + +#endif diff --git a/external/libhv/libhv-1.3.2/event/rudp.h b/external/libhv/libhv-1.3.2/event/rudp.h new file mode 100644 index 0000000..0c30392 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/rudp.h @@ -0,0 +1,52 @@ +#ifndef HV_RUDP_H_ +#define HV_RUDP_H_ + +#include "hloop.h" + +#if WITH_RUDP + +#include "rbtree.h" +#include "hsocket.h" +#include "hmutex.h" +#if WITH_KCP +#include "kcp/hkcp.h" +#endif + +typedef struct rudp_s { + struct rb_root rb_root; + hmutex_t mutex; +} rudp_t; + +typedef struct rudp_entry_s { + struct rb_node rb_node; + sockaddr_u addr; // key + // val + hio_t* io; +#if WITH_KCP + kcp_t kcp; +#endif +} rudp_entry_t; + +// NOTE: rudp_entry_t alloc when rudp_get +void rudp_entry_free(rudp_entry_t* entry); + +void rudp_init(rudp_t* rudp); +void rudp_cleanup(rudp_t* rudp); + +bool rudp_insert(rudp_t* rudp, rudp_entry_t* entry); +// NOTE: just rb_erase, not free +rudp_entry_t* rudp_remove(rudp_t* rudp, struct sockaddr* addr); +rudp_entry_t* rudp_search(rudp_t* rudp, struct sockaddr* addr); +#define rudp_has(rudp, addr) (rudp_search(rudp, addr) != NULL) + +// rudp_search + malloc + rudp_insert +rudp_entry_t* rudp_get(rudp_t* rudp, struct sockaddr* addr); +// rudp_remove + free +void rudp_del(rudp_t* rudp, struct sockaddr* addr); + +// rudp_get(&io->rudp, io->peeraddr) +rudp_entry_t* hio_get_rudp(hio_t* io); + +#endif // WITH_RUDP + +#endif // HV_RUDP_H_ diff --git a/external/libhv/libhv-1.3.2/event/select.c b/external/libhv/libhv-1.3.2/event/select.c new file mode 100644 index 0000000..8a35ea1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/select.c @@ -0,0 +1,169 @@ +#include "iowatcher.h" + +#ifdef EVENT_SELECT +#include "hplatform.h" +#include "hdef.h" +#include "hevent.h" +#include "hsocket.h" + +typedef struct select_ctx_s { + int max_fd; + fd_set readfds; + fd_set writefds; + int nread; + int nwrite; +} select_ctx_t; + +int iowatcher_init(hloop_t* loop) { + if (loop->iowatcher) return 0; + select_ctx_t* select_ctx; + HV_ALLOC_SIZEOF(select_ctx); + select_ctx->max_fd = -1; + FD_ZERO(&select_ctx->readfds); + FD_ZERO(&select_ctx->writefds); + select_ctx->nread = 0; + select_ctx->nwrite = 0; + loop->iowatcher = select_ctx; + return 0; +} + +int iowatcher_cleanup(hloop_t* loop) { + HV_FREE(loop->iowatcher); + return 0; +} + +int iowatcher_add_event(hloop_t* loop, int fd, int events) { + if (loop->iowatcher == NULL) { + iowatcher_init(loop); + } + select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; + if (fd > select_ctx->max_fd) { + select_ctx->max_fd = fd; + } + if (events & HV_READ) { + if (!FD_ISSET(fd, &select_ctx->readfds)) { + FD_SET(fd, &select_ctx->readfds); + select_ctx->nread++; + } + } + if (events & HV_WRITE) { + if (!FD_ISSET(fd, &select_ctx->writefds)) { + FD_SET(fd, &select_ctx->writefds); + select_ctx->nwrite++; + } + } + return 0; +} + +int iowatcher_del_event(hloop_t* loop, int fd, int events) { + select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; + if (select_ctx == NULL) return 0; + if (fd == select_ctx->max_fd) { + select_ctx->max_fd = -1; + } + if (events & HV_READ) { + if (FD_ISSET(fd, &select_ctx->readfds)) { + FD_CLR(fd, &select_ctx->readfds); + select_ctx->nread--; + } + } + if (events & HV_WRITE) { + if (FD_ISSET(fd, &select_ctx->writefds)) { + FD_CLR(fd, &select_ctx->writefds); + select_ctx->nwrite--; + } + } + return 0; +} + +static int find_max_active_fd(hloop_t* loop) { + hio_t* io = NULL; + for (int i = loop->ios.maxsize-1; i >= 0; --i) { + io = loop->ios.ptr[i]; + if (io && io->active && io->events) return i; + } + return -1; +} + +static int remove_bad_fds(hloop_t* loop) { + select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; + if (select_ctx == NULL) return 0; + int badfds = 0; + int error = 0; + socklen_t optlen = sizeof(error); + for (int fd = 0; fd <= select_ctx->max_fd; ++fd) { + if (FD_ISSET(fd, &select_ctx->readfds) || + FD_ISSET(fd, &select_ctx->writefds)) { + error = 0; + optlen = sizeof(int); + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&error, &optlen) < 0 || error != 0) { + ++badfds; + hio_t* io = loop->ios.ptr[fd]; + if (io) { + hio_del(io, HV_RDWR); + } + } + } + } + return badfds; +} + +int iowatcher_poll_events(hloop_t* loop, int timeout) { + select_ctx_t* select_ctx = (select_ctx_t*)loop->iowatcher; + if (select_ctx == NULL) return 0; + if (select_ctx->nread == 0 && select_ctx->nwrite == 0) { + return 0; + } + int max_fd = select_ctx->max_fd; + fd_set readfds = select_ctx->readfds; + fd_set writefds = select_ctx->writefds; + if (max_fd == -1) { + select_ctx->max_fd = max_fd = find_max_active_fd(loop); + } + struct timeval tv, *tp; + if (timeout == INFINITE) { + tp = NULL; + } + else { + tv.tv_sec = timeout / 1000; + tv.tv_usec = (timeout % 1000) * 1000; + tp = &tv; + } + int nselect = select(max_fd+1, &readfds, &writefds, NULL, tp); + if (nselect < 0) { +#ifdef OS_WIN + if (WSAGetLastError() == WSAENOTSOCK) { +#else + if (errno == EBADF) { + perror("select"); +#endif + remove_bad_fds(loop); + return -EBADF; + } + return nselect; + } + if (nselect == 0) return 0; + int nevents = 0; + int revents = 0; + for (int fd = 0; fd <= max_fd; ++fd) { + revents = 0; + if (FD_ISSET(fd, &readfds)) { + ++nevents; + revents |= HV_READ; + } + if (FD_ISSET(fd, &writefds)) { + ++nevents; + revents |= HV_WRITE; + } + if (revents) { + hio_t* io = loop->ios.ptr[fd]; + if (io) { + io->revents = revents; + EVENT_PENDING(io); + } + } + if (nevents == nselect) break; + } + return nevents; +} +#endif diff --git a/external/libhv/libhv-1.3.2/event/unpack.c b/external/libhv/libhv-1.3.2/event/unpack.c new file mode 100644 index 0000000..8a37a26 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/unpack.c @@ -0,0 +1,174 @@ +#include "unpack.h" +#include "hevent.h" +#include "herr.h" +#include "hlog.h" +#include "hmath.h" + +int hio_unpack(hio_t* io, void* buf, int readbytes) { + unpack_setting_t* setting = io->unpack_setting; + switch(setting->mode) { + case UNPACK_BY_FIXED_LENGTH: + return hio_unpack_by_fixed_length(io, buf, readbytes); + case UNPACK_BY_DELIMITER: + return hio_unpack_by_delimiter(io, buf, readbytes); + case UNPACK_BY_LENGTH_FIELD: + return hio_unpack_by_length_field(io, buf, readbytes); + default: + hio_read_cb(io, buf, readbytes); + return readbytes; + } +} + +int hio_unpack_by_fixed_length(hio_t* io, void* buf, int readbytes) { + const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; + const unsigned char* ep = (const unsigned char*)buf + readbytes; + unpack_setting_t* setting = io->unpack_setting; + + int fixed_length = setting->fixed_length; + assert(io->readbuf.len >= fixed_length); + + const unsigned char* p = sp; + int remain = ep - p; + int handled = 0; + while (remain >= fixed_length) { + hio_read_cb(io, (void*)p, fixed_length); + handled += fixed_length; + p += fixed_length; + remain -= fixed_length; + } + + io->readbuf.head = 0; + io->readbuf.tail = remain; + if (remain) { + // [p, p+remain] => [base, base+remain] + if (p != (unsigned char*)io->readbuf.base) { + memmove(io->readbuf.base, p, remain); + } + } + + return handled; +} + +int hio_unpack_by_delimiter(hio_t* io, void* buf, int readbytes) { + const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; + const unsigned char* ep = (const unsigned char*)buf + readbytes; + unpack_setting_t* setting = io->unpack_setting; + + unsigned char* delimiter = setting->delimiter; + int delimiter_bytes = setting->delimiter_bytes; + + const unsigned char* p = (const unsigned char*)buf - delimiter_bytes + 1; + if (p < sp) p = sp; + int remain = ep - p; + int handled = 0; + int i = 0; + while (remain >= delimiter_bytes) { + for (i = 0; i < delimiter_bytes; ++i) { + if (p[i] != delimiter[i]) { + goto not_match; + } + } +match: + p += delimiter_bytes; + remain -= delimiter_bytes; + hio_read_cb(io, (void*)sp, p - sp); + handled += p - sp; + sp = p; + continue; +not_match: + ++p; + --remain; + } + + remain = ep - sp; + io->readbuf.head = 0; + io->readbuf.tail = remain; + if (remain) { + // [sp, sp+remain] => [base, base+remain] + if (sp != (unsigned char*)io->readbuf.base) { + memmove(io->readbuf.base, sp, remain); + } + if (io->readbuf.tail == io->readbuf.len) { + if (io->readbuf.len >= setting->package_max_length) { + hloge("recv package over %d bytes!", (int)setting->package_max_length); + io->error = ERR_OVER_LIMIT; + hio_close(io); + return -1; + } + int newsize = MIN(io->readbuf.len * 2, setting->package_max_length); + hio_alloc_readbuf(io, newsize); + } + } + + return handled; +} + +int hio_unpack_by_length_field(hio_t* io, void* buf, int readbytes) { + const unsigned char* sp = (const unsigned char*)io->readbuf.base + io->readbuf.head; + const unsigned char* ep = (const unsigned char*)buf + readbytes; + unpack_setting_t* setting = io->unpack_setting; + + const unsigned char* p = sp; + int remain = ep - p; + int handled = 0; + unsigned int head_len = setting->body_offset; + unsigned int body_len = 0; + unsigned int package_len = head_len; + const unsigned char* lp = NULL; + while (remain >= setting->body_offset) { + body_len = 0; + lp = p + setting->length_field_offset; + if (setting->length_field_coding == BIG_ENDIAN) { + for (int i = 0; i < setting->length_field_bytes; ++i) { + body_len = (body_len << 8) | (unsigned int)*lp++; + } + } + else if (setting->length_field_coding == LITTLE_ENDIAN) { + for (int i = 0; i < setting->length_field_bytes; ++i) { + body_len |= ((unsigned int)*lp++) << (i * 8); + } + } + else if (setting->length_field_coding == ENCODE_BY_VARINT) { + int varint_bytes = ep - lp; + body_len = varint_decode(lp, &varint_bytes); + if (varint_bytes == 0) break; + if (varint_bytes == -1) { + hloge("varint is too big!"); + io->error = ERR_OVER_LIMIT; + hio_close(io); + return -1; + } + head_len = setting->body_offset + varint_bytes - setting->length_field_bytes; + } + package_len = head_len + body_len + setting->length_adjustment; + if (remain >= package_len) { + hio_read_cb(io, (void*)p, package_len); + handled += package_len; + p += package_len; + remain -= package_len; + } else { + break; + } + } + + io->readbuf.head = 0; + io->readbuf.tail = remain; + if (remain) { + // [p, p+remain] => [base, base+remain] + if (p != (unsigned char*)io->readbuf.base) { + memmove(io->readbuf.base, p, remain); + } + if (package_len > io->readbuf.len) { + if (package_len > setting->package_max_length) { + hloge("package length over %d bytes!", (int)setting->package_max_length); + io->error = ERR_OVER_LIMIT; + hio_close(io); + return -1; + } + int newsize = LIMIT(package_len, io->readbuf.len * 2, setting->package_max_length); + hio_alloc_readbuf(io, newsize); + } + } + + return handled; +} diff --git a/external/libhv/libhv-1.3.2/event/unpack.h b/external/libhv/libhv-1.3.2/event/unpack.h new file mode 100644 index 0000000..3738587 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/unpack.h @@ -0,0 +1,11 @@ +#ifndef HV_UNPACK_H_ +#define HV_UNPACK_H_ + +#include "hloop.h" + +int hio_unpack(hio_t* io, void* buf, int readbytes); +int hio_unpack_by_fixed_length(hio_t* io, void* buf, int readbytes); +int hio_unpack_by_delimiter(hio_t* io, void* buf, int readbytes); +int hio_unpack_by_length_field(hio_t* io, void* buf, int readbytes); + +#endif // HV_UNPACK_H_ diff --git a/external/libhv/libhv-1.3.2/event/wepoll/LICENSE b/external/libhv/libhv-1.3.2/event/wepoll/LICENSE new file mode 100644 index 0000000..d7fc4b1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/wepoll/LICENSE @@ -0,0 +1,28 @@ +wepoll - epoll for Windows +https://github.com/piscisaureus/wepoll + +Copyright 2012-2020, Bert Belder +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. + +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/external/libhv/libhv-1.3.2/event/wepoll/README.md b/external/libhv/libhv-1.3.2/event/wepoll/README.md new file mode 100644 index 0000000..d334d08 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/wepoll/README.md @@ -0,0 +1,202 @@ +# wepoll - epoll for windows + +[![][ci status badge]][ci status link] + +This library implements the [epoll][man epoll] API for Windows +applications. It is fast and scalable, and it closely resembles the API +and behavior of Linux' epoll. + +## Rationale + +Unlike Linux, OS X, and many other operating systems, Windows doesn't +have a good API for receiving socket state notifications. It only +supports the `select` and `WSAPoll` APIs, but they +[don't scale][select scale] and suffer from +[other issues][wsapoll broken]. + +Using I/O completion ports isn't always practical when software is +designed to be cross-platform. Wepoll offers an alternative that is +much closer to a drop-in replacement for software that was designed +to run on Linux. + +## Features + +* Can poll 100000s of sockets efficiently. +* Fully thread-safe. +* Multiple threads can poll the same epoll port. +* Sockets can be added to multiple epoll sets. +* All epoll events (`EPOLLIN`, `EPOLLOUT`, `EPOLLPRI`, `EPOLLRDHUP`) + are supported. +* Level-triggered and one-shot (`EPOLLONESTHOT`) modes are supported +* Trivial to embed: you need [only two files][dist]. + +## Limitations + +* Only works with sockets. +* Edge-triggered (`EPOLLET`) mode isn't supported. + +## How to use + +The library is [distributed][dist] as a single source file +([wepoll.c][wepoll.c]) and a single header file ([wepoll.h][wepoll.h]).
+Compile the .c file as part of your project, and include the header wherever +needed. + +## Compatibility + +* Requires Windows Vista or higher. +* Can be compiled with recent versions of MSVC, Clang, and GCC. + +## API + +### General remarks + +* The epoll port is a `HANDLE`, not a file descriptor. +* All functions set both `errno` and `GetLastError()` on failure. +* For more extensive documentation, see the [epoll(7) man page][man epoll], + and the per-function man pages that are linked below. + +### epoll_create/epoll_create1 + +```c +HANDLE epoll_create(int size); +HANDLE epoll_create1(int flags); +``` + +* Create a new epoll instance (port). +* `size` is ignored but most be greater than zero. +* `flags` must be zero as there are no supported flags. +* Returns `NULL` on failure. +* [Linux man page][man epoll_create] + +### epoll_close + +```c +int epoll_close(HANDLE ephnd); +``` + +* Close an epoll port. +* Do not attempt to close the epoll port with `close()`, + `CloseHandle()` or `closesocket()`. + +### epoll_ctl + +```c +int epoll_ctl(HANDLE ephnd, + int op, + SOCKET sock, + struct epoll_event* event); +``` + +* Control which socket events are monitored by an epoll port. +* `ephnd` must be a HANDLE created by + [`epoll_create()`](#epoll_createepoll_create1) or + [`epoll_create1()`](#epoll_createepoll_create1). +* `op` must be one of `EPOLL_CTL_ADD`, `EPOLL_CTL_MOD`, `EPOLL_CTL_DEL`. +* `sock` must be a valid socket created by [`socket()`][msdn socket], + [`WSASocket()`][msdn wsasocket], or [`accept()`][msdn accept]. +* `event` should be a pointer to a [`struct epoll_event`](#struct-epoll_event).
+ If `op` is `EPOLL_CTL_DEL` then the `event` parameter is ignored, and it + may be `NULL`. +* Returns 0 on success, -1 on failure. +* It is recommended to always explicitly remove a socket from its epoll + set using `EPOLL_CTL_DEL` *before* closing it.
+ As on Linux, closed sockets are automatically removed from the epoll set, but + wepoll may not be able to detect that a socket was closed until the next call + to [`epoll_wait()`](#epoll_wait). +* [Linux man page][man epoll_ctl] + +### epoll_wait + +```c +int epoll_wait(HANDLE ephnd, + struct epoll_event* events, + int maxevents, + int timeout); +``` + +* Receive socket events from an epoll port. +* `events` should point to a caller-allocated array of + [`epoll_event`](#struct-epoll_event) structs, which will receive the + reported events. +* `maxevents` is the maximum number of events that will be written to the + `events` array, and must be greater than zero. +* `timeout` specifies whether to block when no events are immediately available. + - `<0` block indefinitely + - `0` report any events that are already waiting, but don't block + - `≥1` block for at most N milliseconds +* Return value: + - `-1` an error occurred + - `0` timed out without any events to report + - `≥1` the number of events stored in the `events` buffer +* [Linux man page][man epoll_wait] + +### struct epoll_event + +```c +typedef union epoll_data { + void* ptr; + int fd; + uint32_t u32; + uint64_t u64; + SOCKET sock; /* Windows specific */ + HANDLE hnd; /* Windows specific */ +} epoll_data_t; +``` + +```c +struct epoll_event { + uint32_t events; /* Epoll events and flags */ + epoll_data_t data; /* User data variable */ +}; +``` + +* The `events` field is a bit mask containing the events being + monitored/reported, and optional flags.
+ Flags are accepted by [`epoll_ctl()`](#epoll_ctl), but they are not reported + back by [`epoll_wait()`](#epoll_wait). +* The `data` field can be used to associate application-specific information + with a socket; its value will be returned unmodified by + [`epoll_wait()`](#epoll_wait). +* [Linux man page][man epoll_ctl] + +| Event | Description | +|---------------|----------------------------------------------------------------------| +| `EPOLLIN` | incoming data available, or incoming connection ready to be accepted | +| `EPOLLOUT` | ready to send data, or outgoing connection successfully established | +| `EPOLLRDHUP` | remote peer initiated graceful socket shutdown | +| `EPOLLPRI` | out-of-band data available for reading | +| `EPOLLERR` | socket error1 | +| `EPOLLHUP` | socket hang-up1 | +| `EPOLLRDNORM` | same as `EPOLLIN` | +| `EPOLLRDBAND` | same as `EPOLLPRI` | +| `EPOLLWRNORM` | same as `EPOLLOUT` | +| `EPOLLWRBAND` | same as `EPOLLOUT` | +| `EPOLLMSG` | never reported | + +| Flag | Description | +|------------------|---------------------------| +| `EPOLLONESHOT` | report event(s) only once | +| `EPOLLET` | not supported by wepoll | +| `EPOLLEXCLUSIVE` | not supported by wepoll | +| `EPOLLWAKEUP` | not supported by wepoll | + +1: the `EPOLLERR` and `EPOLLHUP` events may always be reported by +[`epoll_wait()`](#epoll_wait), regardless of the event mask that was passed to +[`epoll_ctl()`](#epoll_ctl). + + +[ci status badge]: https://ci.appveyor.com/api/projects/status/github/piscisaureus/wepoll?branch=master&svg=true +[ci status link]: https://ci.appveyor.com/project/piscisaureus/wepoll/branch/master +[dist]: https://github.com/piscisaureus/wepoll/tree/dist +[man epoll]: http://man7.org/linux/man-pages/man7/epoll.7.html +[man epoll_create]: http://man7.org/linux/man-pages/man2/epoll_create.2.html +[man epoll_ctl]: http://man7.org/linux/man-pages/man2/epoll_ctl.2.html +[man epoll_wait]: http://man7.org/linux/man-pages/man2/epoll_wait.2.html +[msdn accept]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms737526(v=vs.85).aspx +[msdn socket]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms740506(v=vs.85).aspx +[msdn wsasocket]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx +[select scale]: https://daniel.haxx.se/docs/poll-vs-select.html +[wsapoll broken]: https://daniel.haxx.se/blog/2012/10/10/wsapoll-is-broken/ +[wepoll.c]: https://github.com/piscisaureus/wepoll/blob/dist/wepoll.c +[wepoll.h]: https://github.com/piscisaureus/wepoll/blob/dist/wepoll.h diff --git a/external/libhv/libhv-1.3.2/event/wepoll/wepoll.c b/external/libhv/libhv-1.3.2/event/wepoll/wepoll.c new file mode 100644 index 0000000..186d3f2 --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/wepoll/wepoll.c @@ -0,0 +1,2253 @@ +/* + * wepoll - epoll for Windows + * https://github.com/piscisaureus/wepoll + * + * Copyright 2012-2020, Bert Belder + * 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. + * + * 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 WEPOLL_EXPORT +#define WEPOLL_EXPORT +#endif + +#include + +enum EPOLL_EVENTS { + EPOLLIN = (int) (1U << 0), + EPOLLPRI = (int) (1U << 1), + EPOLLOUT = (int) (1U << 2), + EPOLLERR = (int) (1U << 3), + EPOLLHUP = (int) (1U << 4), + EPOLLRDNORM = (int) (1U << 6), + EPOLLRDBAND = (int) (1U << 7), + EPOLLWRNORM = (int) (1U << 8), + EPOLLWRBAND = (int) (1U << 9), + EPOLLMSG = (int) (1U << 10), /* Never reported. */ + EPOLLRDHUP = (int) (1U << 13), + EPOLLONESHOT = (int) (1U << 31) +}; + +#define EPOLLIN (1U << 0) +#define EPOLLPRI (1U << 1) +#define EPOLLOUT (1U << 2) +#define EPOLLERR (1U << 3) +#define EPOLLHUP (1U << 4) +#define EPOLLRDNORM (1U << 6) +#define EPOLLRDBAND (1U << 7) +#define EPOLLWRNORM (1U << 8) +#define EPOLLWRBAND (1U << 9) +#define EPOLLMSG (1U << 10) +#define EPOLLRDHUP (1U << 13) +#define EPOLLONESHOT (1U << 31) + +#define EPOLL_CTL_ADD 1 +#define EPOLL_CTL_MOD 2 +#define EPOLL_CTL_DEL 3 + +typedef void* HANDLE; +typedef uintptr_t SOCKET; + +typedef union epoll_data { + void* ptr; + int fd; + uint32_t u32; + uint64_t u64; + SOCKET sock; /* Windows specific */ + HANDLE hnd; /* Windows specific */ +} epoll_data_t; + +struct epoll_event { + uint32_t events; /* Epoll events and flags */ + epoll_data_t data; /* User data variable */ +}; + +#ifdef __cplusplus +extern "C" { +#endif + +WEPOLL_EXPORT HANDLE epoll_create(int size); +WEPOLL_EXPORT HANDLE epoll_create1(int flags); + +WEPOLL_EXPORT int epoll_close(HANDLE ephnd); + +WEPOLL_EXPORT int epoll_ctl(HANDLE ephnd, + int op, + SOCKET sock, + struct epoll_event* event); + +WEPOLL_EXPORT int epoll_wait(HANDLE ephnd, + struct epoll_event* events, + int maxevents, + int timeout); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#include + +#include + +#define WEPOLL_INTERNAL static +#define WEPOLL_INTERNAL_EXTERN static + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonportable-system-include-path" +#pragma clang diagnostic ignored "-Wreserved-id-macro" +#elif defined(_MSC_VER) +#pragma warning(push, 1) +#endif + +#undef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN + +#undef _WIN32_WINNT +#define _WIN32_WINNT 0x0600 + +#include +#include +#include + +#if defined(__clang__) +#pragma clang diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif + +WEPOLL_INTERNAL int nt_global_init(void); + +typedef LONG NTSTATUS; +typedef NTSTATUS* PNTSTATUS; + +#ifndef NT_SUCCESS +#define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0) +#endif + +#ifndef STATUS_SUCCESS +#define STATUS_SUCCESS ((NTSTATUS) 0x00000000L) +#endif + +#ifndef STATUS_PENDING +#define STATUS_PENDING ((NTSTATUS) 0x00000103L) +#endif + +#ifndef STATUS_CANCELLED +#define STATUS_CANCELLED ((NTSTATUS) 0xC0000120L) +#endif + +#ifndef STATUS_NOT_FOUND +#define STATUS_NOT_FOUND ((NTSTATUS) 0xC0000225L) +#endif + +typedef struct _IO_STATUS_BLOCK { + NTSTATUS Status; + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; + +typedef VOID(NTAPI* PIO_APC_ROUTINE)(PVOID ApcContext, + PIO_STATUS_BLOCK IoStatusBlock, + ULONG Reserved); + +typedef struct _UNICODE_STRING { + USHORT Length; + USHORT MaximumLength; + PWSTR Buffer; +} UNICODE_STRING, *PUNICODE_STRING; + +#define RTL_CONSTANT_STRING(s) \ + { sizeof(s) - sizeof((s)[0]), sizeof(s), s } + +typedef struct _OBJECT_ATTRIBUTES { + ULONG Length; + HANDLE RootDirectory; + PUNICODE_STRING ObjectName; + ULONG Attributes; + PVOID SecurityDescriptor; + PVOID SecurityQualityOfService; +} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; + +#define RTL_CONSTANT_OBJECT_ATTRIBUTES(ObjectName, Attributes) \ + { sizeof(OBJECT_ATTRIBUTES), NULL, ObjectName, Attributes, NULL, NULL } + +#ifndef FILE_OPEN +#define FILE_OPEN 0x00000001UL +#endif + +#define KEYEDEVENT_WAIT 0x00000001UL +#define KEYEDEVENT_WAKE 0x00000002UL +#define KEYEDEVENT_ALL_ACCESS \ + (STANDARD_RIGHTS_REQUIRED | KEYEDEVENT_WAIT | KEYEDEVENT_WAKE) + +#define NT_NTDLL_IMPORT_LIST(X) \ + X(NTSTATUS, \ + NTAPI, \ + NtCancelIoFileEx, \ + (HANDLE FileHandle, \ + PIO_STATUS_BLOCK IoRequestToCancel, \ + PIO_STATUS_BLOCK IoStatusBlock)) \ + \ + X(NTSTATUS, \ + NTAPI, \ + NtCreateFile, \ + (PHANDLE FileHandle, \ + ACCESS_MASK DesiredAccess, \ + POBJECT_ATTRIBUTES ObjectAttributes, \ + PIO_STATUS_BLOCK IoStatusBlock, \ + PLARGE_INTEGER AllocationSize, \ + ULONG FileAttributes, \ + ULONG ShareAccess, \ + ULONG CreateDisposition, \ + ULONG CreateOptions, \ + PVOID EaBuffer, \ + ULONG EaLength)) \ + \ + X(NTSTATUS, \ + NTAPI, \ + NtCreateKeyedEvent, \ + (PHANDLE KeyedEventHandle, \ + ACCESS_MASK DesiredAccess, \ + POBJECT_ATTRIBUTES ObjectAttributes, \ + ULONG Flags)) \ + \ + X(NTSTATUS, \ + NTAPI, \ + NtDeviceIoControlFile, \ + (HANDLE FileHandle, \ + HANDLE Event, \ + PIO_APC_ROUTINE ApcRoutine, \ + PVOID ApcContext, \ + PIO_STATUS_BLOCK IoStatusBlock, \ + ULONG IoControlCode, \ + PVOID InputBuffer, \ + ULONG InputBufferLength, \ + PVOID OutputBuffer, \ + ULONG OutputBufferLength)) \ + \ + X(NTSTATUS, \ + NTAPI, \ + NtReleaseKeyedEvent, \ + (HANDLE KeyedEventHandle, \ + PVOID KeyValue, \ + BOOLEAN Alertable, \ + PLARGE_INTEGER Timeout)) \ + \ + X(NTSTATUS, \ + NTAPI, \ + NtWaitForKeyedEvent, \ + (HANDLE KeyedEventHandle, \ + PVOID KeyValue, \ + BOOLEAN Alertable, \ + PLARGE_INTEGER Timeout)) \ + \ + X(ULONG, WINAPI, RtlNtStatusToDosError, (NTSTATUS Status)) + +#define X(return_type, attributes, name, parameters) \ + WEPOLL_INTERNAL_EXTERN return_type(attributes* name) parameters; +NT_NTDLL_IMPORT_LIST(X) +#undef X + +#define AFD_POLL_RECEIVE 0x0001 +#define AFD_POLL_RECEIVE_EXPEDITED 0x0002 +#define AFD_POLL_SEND 0x0004 +#define AFD_POLL_DISCONNECT 0x0008 +#define AFD_POLL_ABORT 0x0010 +#define AFD_POLL_LOCAL_CLOSE 0x0020 +#define AFD_POLL_ACCEPT 0x0080 +#define AFD_POLL_CONNECT_FAIL 0x0100 + +typedef struct _AFD_POLL_HANDLE_INFO { + HANDLE Handle; + ULONG Events; + NTSTATUS Status; +} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO; + +typedef struct _AFD_POLL_INFO { + LARGE_INTEGER Timeout; + ULONG NumberOfHandles; + ULONG Exclusive; + AFD_POLL_HANDLE_INFO Handles[1]; +} AFD_POLL_INFO, *PAFD_POLL_INFO; + +WEPOLL_INTERNAL int afd_create_device_handle(HANDLE iocp_handle, + HANDLE* afd_device_handle_out); + +WEPOLL_INTERNAL int afd_poll(HANDLE afd_device_handle, + AFD_POLL_INFO* poll_info, + IO_STATUS_BLOCK* io_status_block); +WEPOLL_INTERNAL int afd_cancel_poll(HANDLE afd_device_handle, + IO_STATUS_BLOCK* io_status_block); + +#define return_map_error(value) \ + do { \ + err_map_win_error(); \ + return (value); \ + } while (0) + +#define return_set_error(value, error) \ + do { \ + err_set_win_error(error); \ + return (value); \ + } while (0) + +WEPOLL_INTERNAL void err_map_win_error(void); +WEPOLL_INTERNAL void err_set_win_error(DWORD error); +WEPOLL_INTERNAL int err_check_handle(HANDLE handle); + +#define IOCTL_AFD_POLL 0x00012024 + +static UNICODE_STRING afd__device_name = + RTL_CONSTANT_STRING(L"\\Device\\Afd\\Wepoll"); + +static OBJECT_ATTRIBUTES afd__device_attributes = + RTL_CONSTANT_OBJECT_ATTRIBUTES(&afd__device_name, 0); + +int afd_create_device_handle(HANDLE iocp_handle, + HANDLE* afd_device_handle_out) { + HANDLE afd_device_handle; + IO_STATUS_BLOCK iosb; + NTSTATUS status; + + /* By opening \Device\Afd without specifying any extended attributes, we'll + * get a handle that lets us talk to the AFD driver, but that doesn't have an + * associated endpoint (so it's not a socket). */ + status = NtCreateFile(&afd_device_handle, + SYNCHRONIZE, + &afd__device_attributes, + &iosb, + NULL, + 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + FILE_OPEN, + 0, + NULL, + 0); + if (status != STATUS_SUCCESS) + return_set_error(-1, RtlNtStatusToDosError(status)); + + if (CreateIoCompletionPort(afd_device_handle, iocp_handle, 0, 0) == NULL) + goto error; + + if (!SetFileCompletionNotificationModes(afd_device_handle, + FILE_SKIP_SET_EVENT_ON_HANDLE)) + goto error; + + *afd_device_handle_out = afd_device_handle; + return 0; + +error: + CloseHandle(afd_device_handle); + return_map_error(-1); +} + +int afd_poll(HANDLE afd_device_handle, + AFD_POLL_INFO* poll_info, + IO_STATUS_BLOCK* io_status_block) { + NTSTATUS status; + + /* Blocking operation is not supported. */ + assert(io_status_block != NULL); + + io_status_block->Status = STATUS_PENDING; + status = NtDeviceIoControlFile(afd_device_handle, + NULL, + NULL, + io_status_block, + io_status_block, + IOCTL_AFD_POLL, + poll_info, + sizeof *poll_info, + poll_info, + sizeof *poll_info); + + if (status == STATUS_SUCCESS) + return 0; + else if (status == STATUS_PENDING) + return_set_error(-1, ERROR_IO_PENDING); + else + return_set_error(-1, RtlNtStatusToDosError(status)); +} + +int afd_cancel_poll(HANDLE afd_device_handle, + IO_STATUS_BLOCK* io_status_block) { + NTSTATUS cancel_status; + IO_STATUS_BLOCK cancel_iosb; + + /* If the poll operation has already completed or has been cancelled earlier, + * there's nothing left for us to do. */ + if (io_status_block->Status != STATUS_PENDING) + return 0; + + cancel_status = + NtCancelIoFileEx(afd_device_handle, io_status_block, &cancel_iosb); + + /* NtCancelIoFileEx() may return STATUS_NOT_FOUND if the operation completed + * just before calling NtCancelIoFileEx(). This is not an error. */ + if (cancel_status == STATUS_SUCCESS || cancel_status == STATUS_NOT_FOUND) + return 0; + else + return_set_error(-1, RtlNtStatusToDosError(cancel_status)); +} + +WEPOLL_INTERNAL int epoll_global_init(void); + +WEPOLL_INTERNAL int init(void); + +typedef struct port_state port_state_t; +typedef struct queue queue_t; +typedef struct sock_state sock_state_t; +typedef struct ts_tree_node ts_tree_node_t; + +WEPOLL_INTERNAL port_state_t* port_new(HANDLE* iocp_handle_out); +WEPOLL_INTERNAL int port_close(port_state_t* port_state); +WEPOLL_INTERNAL int port_delete(port_state_t* port_state); + +WEPOLL_INTERNAL int port_wait(port_state_t* port_state, + struct epoll_event* events, + int maxevents, + int timeout); + +WEPOLL_INTERNAL int port_ctl(port_state_t* port_state, + int op, + SOCKET sock, + struct epoll_event* ev); + +WEPOLL_INTERNAL int port_register_socket(port_state_t* port_state, + sock_state_t* sock_state, + SOCKET socket); +WEPOLL_INTERNAL void port_unregister_socket(port_state_t* port_state, + sock_state_t* sock_state); +WEPOLL_INTERNAL sock_state_t* port_find_socket(port_state_t* port_state, + SOCKET socket); + +WEPOLL_INTERNAL void port_request_socket_update(port_state_t* port_state, + sock_state_t* sock_state); +WEPOLL_INTERNAL void port_cancel_socket_update(port_state_t* port_state, + sock_state_t* sock_state); + +WEPOLL_INTERNAL void port_add_deleted_socket(port_state_t* port_state, + sock_state_t* sock_state); +WEPOLL_INTERNAL void port_remove_deleted_socket(port_state_t* port_state, + sock_state_t* sock_state); + +WEPOLL_INTERNAL HANDLE port_get_iocp_handle(port_state_t* port_state); +WEPOLL_INTERNAL queue_t* port_get_poll_group_queue(port_state_t* port_state); + +WEPOLL_INTERNAL port_state_t* port_state_from_handle_tree_node( + ts_tree_node_t* tree_node); +WEPOLL_INTERNAL ts_tree_node_t* port_state_to_handle_tree_node( + port_state_t* port_state); + +/* The reflock is a special kind of lock that normally prevents a chunk of + * memory from being freed, but does allow the chunk of memory to eventually be + * released in a coordinated fashion. + * + * Under normal operation, threads increase and decrease the reference count, + * which are wait-free operations. + * + * Exactly once during the reflock's lifecycle, a thread holding a reference to + * the lock may "destroy" the lock; this operation blocks until all other + * threads holding a reference to the lock have dereferenced it. After + * "destroy" returns, the calling thread may assume that no other threads have + * a reference to the lock. + * + * Attemmpting to lock or destroy a lock after reflock_unref_and_destroy() has + * been called is invalid and results in undefined behavior. Therefore the user + * should use another lock to guarantee that this can't happen. + */ + +typedef struct reflock { + volatile long state; /* 32-bit Interlocked APIs operate on `long` values. */ +} reflock_t; + +WEPOLL_INTERNAL int reflock_global_init(void); + +WEPOLL_INTERNAL void reflock_init(reflock_t* reflock); +WEPOLL_INTERNAL void reflock_ref(reflock_t* reflock); +WEPOLL_INTERNAL void reflock_unref(reflock_t* reflock); +WEPOLL_INTERNAL void reflock_unref_and_destroy(reflock_t* reflock); + +#include + +/* N.b.: the tree functions do not set errno or LastError when they fail. Each + * of the API functions has at most one failure mode. It is up to the caller to + * set an appropriate error code when necessary. */ + +typedef struct tree tree_t; +typedef struct tree_node tree_node_t; + +typedef struct tree { + tree_node_t* root; +} tree_t; + +typedef struct tree_node { + tree_node_t* left; + tree_node_t* right; + tree_node_t* parent; + uintptr_t key; + bool red; +} tree_node_t; + +WEPOLL_INTERNAL void tree_init(tree_t* tree); +WEPOLL_INTERNAL void tree_node_init(tree_node_t* node); + +WEPOLL_INTERNAL int tree_add(tree_t* tree, tree_node_t* node, uintptr_t key); +WEPOLL_INTERNAL void tree_del(tree_t* tree, tree_node_t* node); + +WEPOLL_INTERNAL tree_node_t* tree_find(const tree_t* tree, uintptr_t key); +WEPOLL_INTERNAL tree_node_t* tree_root(const tree_t* tree); + +typedef struct ts_tree { + tree_t tree; + SRWLOCK lock; +} ts_tree_t; + +typedef struct ts_tree_node { + tree_node_t tree_node; + reflock_t reflock; +} ts_tree_node_t; + +WEPOLL_INTERNAL void ts_tree_init(ts_tree_t* rtl); +WEPOLL_INTERNAL void ts_tree_node_init(ts_tree_node_t* node); + +WEPOLL_INTERNAL int ts_tree_add(ts_tree_t* ts_tree, + ts_tree_node_t* node, + uintptr_t key); + +WEPOLL_INTERNAL ts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree, + uintptr_t key); +WEPOLL_INTERNAL ts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree, + uintptr_t key); + +WEPOLL_INTERNAL void ts_tree_node_unref(ts_tree_node_t* node); +WEPOLL_INTERNAL void ts_tree_node_unref_and_destroy(ts_tree_node_t* node); + +static ts_tree_t epoll__handle_tree; + +int epoll_global_init(void) { + ts_tree_init(&epoll__handle_tree); + return 0; +} + +static HANDLE epoll__create(void) { + port_state_t* port_state; + HANDLE ephnd; + ts_tree_node_t* tree_node; + + if (init() < 0) + return NULL; + + port_state = port_new(&ephnd); + if (port_state == NULL) + return NULL; + + tree_node = port_state_to_handle_tree_node(port_state); + if (ts_tree_add(&epoll__handle_tree, tree_node, (uintptr_t) ephnd) < 0) { + /* This should never happen. */ + port_delete(port_state); + return_set_error(NULL, ERROR_ALREADY_EXISTS); + } + + return ephnd; +} + +HANDLE epoll_create(int size) { + if (size <= 0) + return_set_error(NULL, ERROR_INVALID_PARAMETER); + + return epoll__create(); +} + +HANDLE epoll_create1(int flags) { + if (flags != 0) + return_set_error(NULL, ERROR_INVALID_PARAMETER); + + return epoll__create(); +} + +int epoll_close(HANDLE ephnd) { + ts_tree_node_t* tree_node; + port_state_t* port_state; + + if (init() < 0) + return -1; + + tree_node = ts_tree_del_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); + if (tree_node == NULL) { + err_set_win_error(ERROR_INVALID_PARAMETER); + goto err; + } + + port_state = port_state_from_handle_tree_node(tree_node); + port_close(port_state); + + ts_tree_node_unref_and_destroy(tree_node); + + return port_delete(port_state); + +err: + err_check_handle(ephnd); + return -1; +} + +int epoll_ctl(HANDLE ephnd, int op, SOCKET sock, struct epoll_event* ev) { + ts_tree_node_t* tree_node; + port_state_t* port_state; + int r; + + if (init() < 0) + return -1; + + tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); + if (tree_node == NULL) { + err_set_win_error(ERROR_INVALID_PARAMETER); + goto err; + } + + port_state = port_state_from_handle_tree_node(tree_node); + r = port_ctl(port_state, op, sock, ev); + + ts_tree_node_unref(tree_node); + + if (r < 0) + goto err; + + return 0; + +err: + /* On Linux, in the case of epoll_ctl(), EBADF takes priority over other + * errors. Wepoll mimics this behavior. */ + err_check_handle(ephnd); + err_check_handle((HANDLE) sock); + return -1; +} + +int epoll_wait(HANDLE ephnd, + struct epoll_event* events, + int maxevents, + int timeout) { + ts_tree_node_t* tree_node; + port_state_t* port_state; + int num_events; + + if (maxevents <= 0) + return_set_error(-1, ERROR_INVALID_PARAMETER); + + if (init() < 0) + return -1; + + tree_node = ts_tree_find_and_ref(&epoll__handle_tree, (uintptr_t) ephnd); + if (tree_node == NULL) { + err_set_win_error(ERROR_INVALID_PARAMETER); + goto err; + } + + port_state = port_state_from_handle_tree_node(tree_node); + num_events = port_wait(port_state, events, maxevents, timeout); + + ts_tree_node_unref(tree_node); + + if (num_events < 0) + goto err; + + return num_events; + +err: + err_check_handle(ephnd); + return -1; +} + +#include + +#define ERR__ERRNO_MAPPINGS(X) \ + X(ERROR_ACCESS_DENIED, EACCES) \ + X(ERROR_ALREADY_EXISTS, EEXIST) \ + X(ERROR_BAD_COMMAND, EACCES) \ + X(ERROR_BAD_EXE_FORMAT, ENOEXEC) \ + X(ERROR_BAD_LENGTH, EACCES) \ + X(ERROR_BAD_NETPATH, ENOENT) \ + X(ERROR_BAD_NET_NAME, ENOENT) \ + X(ERROR_BAD_NET_RESP, ENETDOWN) \ + X(ERROR_BAD_PATHNAME, ENOENT) \ + X(ERROR_BROKEN_PIPE, EPIPE) \ + X(ERROR_CANNOT_MAKE, EACCES) \ + X(ERROR_COMMITMENT_LIMIT, ENOMEM) \ + X(ERROR_CONNECTION_ABORTED, ECONNABORTED) \ + X(ERROR_CONNECTION_ACTIVE, EISCONN) \ + X(ERROR_CONNECTION_REFUSED, ECONNREFUSED) \ + X(ERROR_CRC, EACCES) \ + X(ERROR_DIR_NOT_EMPTY, ENOTEMPTY) \ + X(ERROR_DISK_FULL, ENOSPC) \ + X(ERROR_DUP_NAME, EADDRINUSE) \ + X(ERROR_FILENAME_EXCED_RANGE, ENOENT) \ + X(ERROR_FILE_NOT_FOUND, ENOENT) \ + X(ERROR_GEN_FAILURE, EACCES) \ + X(ERROR_GRACEFUL_DISCONNECT, EPIPE) \ + X(ERROR_HOST_DOWN, EHOSTUNREACH) \ + X(ERROR_HOST_UNREACHABLE, EHOSTUNREACH) \ + X(ERROR_INSUFFICIENT_BUFFER, EFAULT) \ + X(ERROR_INVALID_ADDRESS, EADDRNOTAVAIL) \ + X(ERROR_INVALID_FUNCTION, EINVAL) \ + X(ERROR_INVALID_HANDLE, EBADF) \ + X(ERROR_INVALID_NETNAME, EADDRNOTAVAIL) \ + X(ERROR_INVALID_PARAMETER, EINVAL) \ + X(ERROR_INVALID_USER_BUFFER, EMSGSIZE) \ + X(ERROR_IO_PENDING, EINPROGRESS) \ + X(ERROR_LOCK_VIOLATION, EACCES) \ + X(ERROR_MORE_DATA, EMSGSIZE) \ + X(ERROR_NETNAME_DELETED, ECONNABORTED) \ + X(ERROR_NETWORK_ACCESS_DENIED, EACCES) \ + X(ERROR_NETWORK_BUSY, ENETDOWN) \ + X(ERROR_NETWORK_UNREACHABLE, ENETUNREACH) \ + X(ERROR_NOACCESS, EFAULT) \ + X(ERROR_NONPAGED_SYSTEM_RESOURCES, ENOMEM) \ + X(ERROR_NOT_ENOUGH_MEMORY, ENOMEM) \ + X(ERROR_NOT_ENOUGH_QUOTA, ENOMEM) \ + X(ERROR_NOT_FOUND, ENOENT) \ + X(ERROR_NOT_LOCKED, EACCES) \ + X(ERROR_NOT_READY, EACCES) \ + X(ERROR_NOT_SAME_DEVICE, EXDEV) \ + X(ERROR_NOT_SUPPORTED, ENOTSUP) \ + X(ERROR_NO_MORE_FILES, ENOENT) \ + X(ERROR_NO_SYSTEM_RESOURCES, ENOMEM) \ + X(ERROR_OPERATION_ABORTED, EINTR) \ + X(ERROR_OUT_OF_PAPER, EACCES) \ + X(ERROR_PAGED_SYSTEM_RESOURCES, ENOMEM) \ + X(ERROR_PAGEFILE_QUOTA, ENOMEM) \ + X(ERROR_PATH_NOT_FOUND, ENOENT) \ + X(ERROR_PIPE_NOT_CONNECTED, EPIPE) \ + X(ERROR_PORT_UNREACHABLE, ECONNRESET) \ + X(ERROR_PROTOCOL_UNREACHABLE, ENETUNREACH) \ + X(ERROR_REM_NOT_LIST, ECONNREFUSED) \ + X(ERROR_REQUEST_ABORTED, EINTR) \ + X(ERROR_REQ_NOT_ACCEP, EWOULDBLOCK) \ + X(ERROR_SECTOR_NOT_FOUND, EACCES) \ + X(ERROR_SEM_TIMEOUT, ETIMEDOUT) \ + X(ERROR_SHARING_VIOLATION, EACCES) \ + X(ERROR_TOO_MANY_NAMES, ENOMEM) \ + X(ERROR_TOO_MANY_OPEN_FILES, EMFILE) \ + X(ERROR_UNEXP_NET_ERR, ECONNABORTED) \ + X(ERROR_WAIT_NO_CHILDREN, ECHILD) \ + X(ERROR_WORKING_SET_QUOTA, ENOMEM) \ + X(ERROR_WRITE_PROTECT, EACCES) \ + X(ERROR_WRONG_DISK, EACCES) \ + X(WSAEACCES, EACCES) \ + X(WSAEADDRINUSE, EADDRINUSE) \ + X(WSAEADDRNOTAVAIL, EADDRNOTAVAIL) \ + X(WSAEAFNOSUPPORT, EAFNOSUPPORT) \ + X(WSAECONNABORTED, ECONNABORTED) \ + X(WSAECONNREFUSED, ECONNREFUSED) \ + X(WSAECONNRESET, ECONNRESET) \ + X(WSAEDISCON, EPIPE) \ + X(WSAEFAULT, EFAULT) \ + X(WSAEHOSTDOWN, EHOSTUNREACH) \ + X(WSAEHOSTUNREACH, EHOSTUNREACH) \ + X(WSAEINPROGRESS, EBUSY) \ + X(WSAEINTR, EINTR) \ + X(WSAEINVAL, EINVAL) \ + X(WSAEISCONN, EISCONN) \ + X(WSAEMSGSIZE, EMSGSIZE) \ + X(WSAENETDOWN, ENETDOWN) \ + X(WSAENETRESET, EHOSTUNREACH) \ + X(WSAENETUNREACH, ENETUNREACH) \ + X(WSAENOBUFS, ENOMEM) \ + X(WSAENOTCONN, ENOTCONN) \ + X(WSAENOTSOCK, ENOTSOCK) \ + X(WSAEOPNOTSUPP, EOPNOTSUPP) \ + X(WSAEPROCLIM, ENOMEM) \ + X(WSAESHUTDOWN, EPIPE) \ + X(WSAETIMEDOUT, ETIMEDOUT) \ + X(WSAEWOULDBLOCK, EWOULDBLOCK) \ + X(WSANOTINITIALISED, ENETDOWN) \ + X(WSASYSNOTREADY, ENETDOWN) \ + X(WSAVERNOTSUPPORTED, ENOSYS) + +static errno_t err__map_win_error_to_errno(DWORD error) { + switch (error) { +#define X(error_sym, errno_sym) \ + case error_sym: \ + return errno_sym; + ERR__ERRNO_MAPPINGS(X) +#undef X + } + return EINVAL; +} + +void err_map_win_error(void) { + errno = err__map_win_error_to_errno(GetLastError()); +} + +void err_set_win_error(DWORD error) { + SetLastError(error); + errno = err__map_win_error_to_errno(error); +} + +int err_check_handle(HANDLE handle) { + DWORD flags; + + /* GetHandleInformation() succeeds when passed INVALID_HANDLE_VALUE, so check + * for this condition explicitly. */ + if (handle == INVALID_HANDLE_VALUE) + return_set_error(-1, ERROR_INVALID_HANDLE); + + if (!GetHandleInformation(handle, &flags)) + return_map_error(-1); + + return 0; +} + +#include + +#define array_count(a) (sizeof(a) / (sizeof((a)[0]))) + +#define container_of(ptr, type, member) \ + ((type*) ((uintptr_t) (ptr) - offsetof(type, member))) + +#define unused_var(v) ((void) (v)) + +/* Polyfill `inline` for older versions of msvc (up to Visual Studio 2013) */ +#if defined(_MSC_VER) && _MSC_VER < 1900 +#define inline __inline +#endif + +WEPOLL_INTERNAL int ws_global_init(void); +WEPOLL_INTERNAL SOCKET ws_get_base_socket(SOCKET socket); + +static bool init__done = false; +static INIT_ONCE init__once = INIT_ONCE_STATIC_INIT; + +static BOOL CALLBACK init__once_callback(INIT_ONCE* once, + void* parameter, + void** context) { + unused_var(once); + unused_var(parameter); + unused_var(context); + + /* N.b. that initialization order matters here. */ + if (ws_global_init() < 0 || nt_global_init() < 0 || + reflock_global_init() < 0 || epoll_global_init() < 0) + return FALSE; + + init__done = true; + return TRUE; +} + +int init(void) { + if (!init__done && + !InitOnceExecuteOnce(&init__once, init__once_callback, NULL, NULL)) + /* `InitOnceExecuteOnce()` itself is infallible, and it doesn't set any + * error code when the once-callback returns FALSE. We return -1 here to + * indicate that global initialization failed; the failing init function is + * resposible for setting `errno` and calling `SetLastError()`. */ + return -1; + + return 0; +} + +/* Set up a workaround for the following problem: + * FARPROC addr = GetProcAddress(...); + * MY_FUNC func = (MY_FUNC) addr; <-- GCC 8 warning/error. + * MY_FUNC func = (MY_FUNC) (void*) addr; <-- MSVC warning/error. + * To compile cleanly with either compiler, do casts with this "bridge" type: + * MY_FUNC func = (MY_FUNC) (nt__fn_ptr_cast_t) addr; */ +#ifdef __GNUC__ +typedef void* nt__fn_ptr_cast_t; +#else +typedef FARPROC nt__fn_ptr_cast_t; +#endif + +#define X(return_type, attributes, name, parameters) \ + WEPOLL_INTERNAL return_type(attributes* name) parameters = NULL; +NT_NTDLL_IMPORT_LIST(X) +#undef X + +int nt_global_init(void) { + HMODULE ntdll; + FARPROC fn_ptr; + + ntdll = GetModuleHandleW(L"ntdll.dll"); + if (ntdll == NULL) + return -1; + +#define X(return_type, attributes, name, parameters) \ + fn_ptr = GetProcAddress(ntdll, #name); \ + if (fn_ptr == NULL) \ + return -1; \ + name = (return_type(attributes*) parameters)(nt__fn_ptr_cast_t) fn_ptr; + NT_NTDLL_IMPORT_LIST(X) +#undef X + + return 0; +} + +#include + +typedef struct poll_group poll_group_t; + +typedef struct queue_node queue_node_t; + +WEPOLL_INTERNAL poll_group_t* poll_group_acquire(port_state_t* port); +WEPOLL_INTERNAL void poll_group_release(poll_group_t* poll_group); + +WEPOLL_INTERNAL void poll_group_delete(poll_group_t* poll_group); + +WEPOLL_INTERNAL poll_group_t* poll_group_from_queue_node( + queue_node_t* queue_node); +WEPOLL_INTERNAL HANDLE + poll_group_get_afd_device_handle(poll_group_t* poll_group); + +typedef struct queue_node { + queue_node_t* prev; + queue_node_t* next; +} queue_node_t; + +typedef struct queue { + queue_node_t head; +} queue_t; + +WEPOLL_INTERNAL void queue_init(queue_t* queue); +WEPOLL_INTERNAL void queue_node_init(queue_node_t* node); + +WEPOLL_INTERNAL queue_node_t* queue_first(const queue_t* queue); +WEPOLL_INTERNAL queue_node_t* queue_last(const queue_t* queue); + +WEPOLL_INTERNAL void queue_prepend(queue_t* queue, queue_node_t* node); +WEPOLL_INTERNAL void queue_append(queue_t* queue, queue_node_t* node); +WEPOLL_INTERNAL void queue_move_to_start(queue_t* queue, queue_node_t* node); +WEPOLL_INTERNAL void queue_move_to_end(queue_t* queue, queue_node_t* node); +WEPOLL_INTERNAL void queue_remove(queue_node_t* node); + +WEPOLL_INTERNAL bool queue_is_empty(const queue_t* queue); +WEPOLL_INTERNAL bool queue_is_enqueued(const queue_node_t* node); + +#define POLL_GROUP__MAX_GROUP_SIZE 32 + +typedef struct poll_group { + port_state_t* port_state; + queue_node_t queue_node; + HANDLE afd_device_handle; + size_t group_size; +} poll_group_t; + +static poll_group_t* poll_group__new(port_state_t* port_state) { + HANDLE iocp_handle = port_get_iocp_handle(port_state); + queue_t* poll_group_queue = port_get_poll_group_queue(port_state); + + poll_group_t* poll_group = malloc(sizeof *poll_group); + if (poll_group == NULL) + return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); + + memset(poll_group, 0, sizeof *poll_group); + + queue_node_init(&poll_group->queue_node); + poll_group->port_state = port_state; + + if (afd_create_device_handle(iocp_handle, &poll_group->afd_device_handle) < + 0) { + free(poll_group); + return NULL; + } + + queue_append(poll_group_queue, &poll_group->queue_node); + + return poll_group; +} + +void poll_group_delete(poll_group_t* poll_group) { + assert(poll_group->group_size == 0); + CloseHandle(poll_group->afd_device_handle); + queue_remove(&poll_group->queue_node); + free(poll_group); +} + +poll_group_t* poll_group_from_queue_node(queue_node_t* queue_node) { + return container_of(queue_node, poll_group_t, queue_node); +} + +HANDLE poll_group_get_afd_device_handle(poll_group_t* poll_group) { + return poll_group->afd_device_handle; +} + +poll_group_t* poll_group_acquire(port_state_t* port_state) { + queue_t* poll_group_queue = port_get_poll_group_queue(port_state); + poll_group_t* poll_group = + !queue_is_empty(poll_group_queue) + ? container_of( + queue_last(poll_group_queue), poll_group_t, queue_node) + : NULL; + + if (poll_group == NULL || + poll_group->group_size >= POLL_GROUP__MAX_GROUP_SIZE) + poll_group = poll_group__new(port_state); + if (poll_group == NULL) + return NULL; + + if (++poll_group->group_size == POLL_GROUP__MAX_GROUP_SIZE) + queue_move_to_start(poll_group_queue, &poll_group->queue_node); + + return poll_group; +} + +void poll_group_release(poll_group_t* poll_group) { + port_state_t* port_state = poll_group->port_state; + queue_t* poll_group_queue = port_get_poll_group_queue(port_state); + + poll_group->group_size--; + assert(poll_group->group_size < POLL_GROUP__MAX_GROUP_SIZE); + + queue_move_to_end(poll_group_queue, &poll_group->queue_node); + + /* Poll groups are currently only freed when the epoll port is closed. */ +} + +WEPOLL_INTERNAL sock_state_t* sock_new(port_state_t* port_state, + SOCKET socket); +WEPOLL_INTERNAL void sock_delete(port_state_t* port_state, + sock_state_t* sock_state); +WEPOLL_INTERNAL void sock_force_delete(port_state_t* port_state, + sock_state_t* sock_state); + +WEPOLL_INTERNAL int sock_set_event(port_state_t* port_state, + sock_state_t* sock_state, + const struct epoll_event* ev); + +WEPOLL_INTERNAL int sock_update(port_state_t* port_state, + sock_state_t* sock_state); +WEPOLL_INTERNAL int sock_feed_event(port_state_t* port_state, + IO_STATUS_BLOCK* io_status_block, + struct epoll_event* ev); + +WEPOLL_INTERNAL sock_state_t* sock_state_from_queue_node( + queue_node_t* queue_node); +WEPOLL_INTERNAL queue_node_t* sock_state_to_queue_node( + sock_state_t* sock_state); +WEPOLL_INTERNAL sock_state_t* sock_state_from_tree_node( + tree_node_t* tree_node); +WEPOLL_INTERNAL tree_node_t* sock_state_to_tree_node(sock_state_t* sock_state); + +#define PORT__MAX_ON_STACK_COMPLETIONS 256 + +typedef struct port_state { + HANDLE iocp_handle; + tree_t sock_tree; + queue_t sock_update_queue; + queue_t sock_deleted_queue; + queue_t poll_group_queue; + ts_tree_node_t handle_tree_node; + CRITICAL_SECTION lock; + size_t active_poll_count; +} port_state_t; + +static inline port_state_t* port__alloc(void) { + port_state_t* port_state = malloc(sizeof *port_state); + if (port_state == NULL) + return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); + + return port_state; +} + +static inline void port__free(port_state_t* port) { + assert(port != NULL); + free(port); +} + +static inline HANDLE port__create_iocp(void) { + HANDLE iocp_handle = + CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0); + if (iocp_handle == NULL) + return_map_error(NULL); + + return iocp_handle; +} + +port_state_t* port_new(HANDLE* iocp_handle_out) { + port_state_t* port_state; + HANDLE iocp_handle; + + port_state = port__alloc(); + if (port_state == NULL) + goto err1; + + iocp_handle = port__create_iocp(); + if (iocp_handle == NULL) + goto err2; + + memset(port_state, 0, sizeof *port_state); + + port_state->iocp_handle = iocp_handle; + tree_init(&port_state->sock_tree); + queue_init(&port_state->sock_update_queue); + queue_init(&port_state->sock_deleted_queue); + queue_init(&port_state->poll_group_queue); + ts_tree_node_init(&port_state->handle_tree_node); + InitializeCriticalSection(&port_state->lock); + + *iocp_handle_out = iocp_handle; + return port_state; + +err2: + port__free(port_state); +err1: + return NULL; +} + +static inline int port__close_iocp(port_state_t* port_state) { + HANDLE iocp_handle = port_state->iocp_handle; + port_state->iocp_handle = NULL; + + if (!CloseHandle(iocp_handle)) + return_map_error(-1); + + return 0; +} + +int port_close(port_state_t* port_state) { + int result; + + EnterCriticalSection(&port_state->lock); + result = port__close_iocp(port_state); + LeaveCriticalSection(&port_state->lock); + + return result; +} + +int port_delete(port_state_t* port_state) { + tree_node_t* tree_node; + queue_node_t* queue_node; + + /* At this point the IOCP port should have been closed. */ + assert(port_state->iocp_handle == NULL); + + while ((tree_node = tree_root(&port_state->sock_tree)) != NULL) { + sock_state_t* sock_state = sock_state_from_tree_node(tree_node); + sock_force_delete(port_state, sock_state); + } + + while ((queue_node = queue_first(&port_state->sock_deleted_queue)) != NULL) { + sock_state_t* sock_state = sock_state_from_queue_node(queue_node); + sock_force_delete(port_state, sock_state); + } + + while ((queue_node = queue_first(&port_state->poll_group_queue)) != NULL) { + poll_group_t* poll_group = poll_group_from_queue_node(queue_node); + poll_group_delete(poll_group); + } + + assert(queue_is_empty(&port_state->sock_update_queue)); + + DeleteCriticalSection(&port_state->lock); + + port__free(port_state); + + return 0; +} + +static int port__update_events(port_state_t* port_state) { + queue_t* sock_update_queue = &port_state->sock_update_queue; + + /* Walk the queue, submitting new poll requests for every socket that needs + * it. */ + while (!queue_is_empty(sock_update_queue)) { + queue_node_t* queue_node = queue_first(sock_update_queue); + sock_state_t* sock_state = sock_state_from_queue_node(queue_node); + + if (sock_update(port_state, sock_state) < 0) + return -1; + + /* sock_update() removes the socket from the update queue. */ + } + + return 0; +} + +static inline void port__update_events_if_polling(port_state_t* port_state) { + if (port_state->active_poll_count > 0) + port__update_events(port_state); +} + +static inline int port__feed_events(port_state_t* port_state, + struct epoll_event* epoll_events, + OVERLAPPED_ENTRY* iocp_events, + DWORD iocp_event_count) { + int epoll_event_count = 0; + DWORD i; + + for (i = 0; i < iocp_event_count; i++) { + IO_STATUS_BLOCK* io_status_block = + (IO_STATUS_BLOCK*) iocp_events[i].lpOverlapped; + struct epoll_event* ev = &epoll_events[epoll_event_count]; + + epoll_event_count += sock_feed_event(port_state, io_status_block, ev); + } + + return epoll_event_count; +} + +static inline int port__poll(port_state_t* port_state, + struct epoll_event* epoll_events, + OVERLAPPED_ENTRY* iocp_events, + DWORD maxevents, + DWORD timeout) { + DWORD completion_count; + + if (port__update_events(port_state) < 0) + return -1; + + port_state->active_poll_count++; + + LeaveCriticalSection(&port_state->lock); + + BOOL r = GetQueuedCompletionStatusEx(port_state->iocp_handle, + iocp_events, + maxevents, + &completion_count, + timeout, + FALSE); + + EnterCriticalSection(&port_state->lock); + + port_state->active_poll_count--; + + if (!r) + return_map_error(-1); + + return port__feed_events( + port_state, epoll_events, iocp_events, completion_count); +} + +int port_wait(port_state_t* port_state, + struct epoll_event* events, + int maxevents, + int timeout) { + OVERLAPPED_ENTRY stack_iocp_events[PORT__MAX_ON_STACK_COMPLETIONS]; + OVERLAPPED_ENTRY* iocp_events; + uint64_t due = 0; + DWORD gqcs_timeout; + int result; + + /* Check whether `maxevents` is in range. */ + if (maxevents <= 0) + return_set_error(-1, ERROR_INVALID_PARAMETER); + + /* Decide whether the IOCP completion list can live on the stack, or allocate + * memory for it on the heap. */ + if ((size_t) maxevents <= array_count(stack_iocp_events)) { + iocp_events = stack_iocp_events; + } else if ((iocp_events = + malloc((size_t) maxevents * sizeof *iocp_events)) == NULL) { + iocp_events = stack_iocp_events; + maxevents = array_count(stack_iocp_events); + } + + /* Compute the timeout for GetQueuedCompletionStatus, and the wait end + * time, if the user specified a timeout other than zero or infinite. */ + if (timeout > 0) { + due = GetTickCount64() + (uint64_t) timeout; + gqcs_timeout = (DWORD) timeout; + } else if (timeout == 0) { + gqcs_timeout = 0; + } else { + gqcs_timeout = INFINITE; + } + + EnterCriticalSection(&port_state->lock); + + /* Dequeue completion packets until either at least one interesting event + * has been discovered, or the timeout is reached. */ + for (;;) { + uint64_t now; + + result = port__poll( + port_state, events, iocp_events, (DWORD) maxevents, gqcs_timeout); + if (result < 0 || result > 0) + break; /* Result, error, or time-out. */ + + if (timeout < 0) + continue; /* When timeout is negative, never time out. */ + + /* Update time. */ + now = GetTickCount64(); + + /* Do not allow the due time to be in the past. */ + if (now >= due) { + SetLastError(WAIT_TIMEOUT); + break; + } + + /* Recompute time-out argument for GetQueuedCompletionStatus. */ + gqcs_timeout = (DWORD)(due - now); + } + + port__update_events_if_polling(port_state); + + LeaveCriticalSection(&port_state->lock); + + if (iocp_events != stack_iocp_events) + free(iocp_events); + + if (result >= 0) + return result; + else if (GetLastError() == WAIT_TIMEOUT) + return 0; + else + return -1; +} + +static inline int port__ctl_add(port_state_t* port_state, + SOCKET sock, + struct epoll_event* ev) { + sock_state_t* sock_state = sock_new(port_state, sock); + if (sock_state == NULL) + return -1; + + if (sock_set_event(port_state, sock_state, ev) < 0) { + sock_delete(port_state, sock_state); + return -1; + } + + port__update_events_if_polling(port_state); + + return 0; +} + +static inline int port__ctl_mod(port_state_t* port_state, + SOCKET sock, + struct epoll_event* ev) { + sock_state_t* sock_state = port_find_socket(port_state, sock); + if (sock_state == NULL) + return -1; + + if (sock_set_event(port_state, sock_state, ev) < 0) + return -1; + + port__update_events_if_polling(port_state); + + return 0; +} + +static inline int port__ctl_del(port_state_t* port_state, SOCKET sock) { + sock_state_t* sock_state = port_find_socket(port_state, sock); + if (sock_state == NULL) + return -1; + + sock_delete(port_state, sock_state); + + return 0; +} + +static inline int port__ctl_op(port_state_t* port_state, + int op, + SOCKET sock, + struct epoll_event* ev) { + switch (op) { + case EPOLL_CTL_ADD: + return port__ctl_add(port_state, sock, ev); + case EPOLL_CTL_MOD: + return port__ctl_mod(port_state, sock, ev); + case EPOLL_CTL_DEL: + return port__ctl_del(port_state, sock); + default: + return_set_error(-1, ERROR_INVALID_PARAMETER); + } +} + +int port_ctl(port_state_t* port_state, + int op, + SOCKET sock, + struct epoll_event* ev) { + int result; + + EnterCriticalSection(&port_state->lock); + result = port__ctl_op(port_state, op, sock, ev); + LeaveCriticalSection(&port_state->lock); + + return result; +} + +int port_register_socket(port_state_t* port_state, + sock_state_t* sock_state, + SOCKET socket) { + if (tree_add(&port_state->sock_tree, + sock_state_to_tree_node(sock_state), + socket) < 0) + return_set_error(-1, ERROR_ALREADY_EXISTS); + return 0; +} + +void port_unregister_socket(port_state_t* port_state, + sock_state_t* sock_state) { + tree_del(&port_state->sock_tree, sock_state_to_tree_node(sock_state)); +} + +sock_state_t* port_find_socket(port_state_t* port_state, SOCKET socket) { + tree_node_t* tree_node = tree_find(&port_state->sock_tree, socket); + if (tree_node == NULL) + return_set_error(NULL, ERROR_NOT_FOUND); + return sock_state_from_tree_node(tree_node); +} + +void port_request_socket_update(port_state_t* port_state, + sock_state_t* sock_state) { + if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) + return; + queue_append(&port_state->sock_update_queue, + sock_state_to_queue_node(sock_state)); +} + +void port_cancel_socket_update(port_state_t* port_state, + sock_state_t* sock_state) { + unused_var(port_state); + if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) + return; + queue_remove(sock_state_to_queue_node(sock_state)); +} + +void port_add_deleted_socket(port_state_t* port_state, + sock_state_t* sock_state) { + if (queue_is_enqueued(sock_state_to_queue_node(sock_state))) + return; + queue_append(&port_state->sock_deleted_queue, + sock_state_to_queue_node(sock_state)); +} + +void port_remove_deleted_socket(port_state_t* port_state, + sock_state_t* sock_state) { + unused_var(port_state); + if (!queue_is_enqueued(sock_state_to_queue_node(sock_state))) + return; + queue_remove(sock_state_to_queue_node(sock_state)); +} + +HANDLE port_get_iocp_handle(port_state_t* port_state) { + assert(port_state->iocp_handle != NULL); + return port_state->iocp_handle; +} + +queue_t* port_get_poll_group_queue(port_state_t* port_state) { + return &port_state->poll_group_queue; +} + +port_state_t* port_state_from_handle_tree_node(ts_tree_node_t* tree_node) { + return container_of(tree_node, port_state_t, handle_tree_node); +} + +ts_tree_node_t* port_state_to_handle_tree_node(port_state_t* port_state) { + return &port_state->handle_tree_node; +} + +void queue_init(queue_t* queue) { + queue_node_init(&queue->head); +} + +void queue_node_init(queue_node_t* node) { + node->prev = node; + node->next = node; +} + +static inline void queue__detach_node(queue_node_t* node) { + node->prev->next = node->next; + node->next->prev = node->prev; +} + +queue_node_t* queue_first(const queue_t* queue) { + return !queue_is_empty(queue) ? queue->head.next : NULL; +} + +queue_node_t* queue_last(const queue_t* queue) { + return !queue_is_empty(queue) ? queue->head.prev : NULL; +} + +void queue_prepend(queue_t* queue, queue_node_t* node) { + node->next = queue->head.next; + node->prev = &queue->head; + node->next->prev = node; + queue->head.next = node; +} + +void queue_append(queue_t* queue, queue_node_t* node) { + node->next = &queue->head; + node->prev = queue->head.prev; + node->prev->next = node; + queue->head.prev = node; +} + +void queue_move_to_start(queue_t* queue, queue_node_t* node) { + queue__detach_node(node); + queue_prepend(queue, node); +} + +void queue_move_to_end(queue_t* queue, queue_node_t* node) { + queue__detach_node(node); + queue_append(queue, node); +} + +void queue_remove(queue_node_t* node) { + queue__detach_node(node); + queue_node_init(node); +} + +bool queue_is_empty(const queue_t* queue) { + return !queue_is_enqueued(&queue->head); +} + +bool queue_is_enqueued(const queue_node_t* node) { + return node->prev != node; +} + +#define REFLOCK__REF ((long) 0x00000001UL) +#define REFLOCK__REF_MASK ((long) 0x0fffffffUL) +#define REFLOCK__DESTROY ((long) 0x10000000UL) +#define REFLOCK__DESTROY_MASK ((long) 0xf0000000UL) +#define REFLOCK__POISON ((long) 0x300dead0UL) + +static HANDLE reflock__keyed_event = NULL; + +int reflock_global_init(void) { + NTSTATUS status = NtCreateKeyedEvent( + &reflock__keyed_event, KEYEDEVENT_ALL_ACCESS, NULL, 0); + if (status != STATUS_SUCCESS) + return_set_error(-1, RtlNtStatusToDosError(status)); + return 0; +} + +void reflock_init(reflock_t* reflock) { + reflock->state = 0; +} + +static void reflock__signal_event(void* address) { + NTSTATUS status = + NtReleaseKeyedEvent(reflock__keyed_event, address, FALSE, NULL); + if (status != STATUS_SUCCESS) + abort(); +} + +static void reflock__await_event(void* address) { + NTSTATUS status = + NtWaitForKeyedEvent(reflock__keyed_event, address, FALSE, NULL); + if (status != STATUS_SUCCESS) + abort(); +} + +void reflock_ref(reflock_t* reflock) { + long state = InterlockedAdd(&reflock->state, REFLOCK__REF); + + /* Verify that the counter didn't overflow and the lock isn't destroyed. */ + assert((state & REFLOCK__DESTROY_MASK) == 0); + unused_var(state); +} + +void reflock_unref(reflock_t* reflock) { + long state = InterlockedAdd(&reflock->state, -REFLOCK__REF); + + /* Verify that the lock was referenced and not already destroyed. */ + assert((state & REFLOCK__DESTROY_MASK & ~REFLOCK__DESTROY) == 0); + + if (state == REFLOCK__DESTROY) + reflock__signal_event(reflock); +} + +void reflock_unref_and_destroy(reflock_t* reflock) { + long state = + InterlockedAdd(&reflock->state, REFLOCK__DESTROY - REFLOCK__REF); + long ref_count = state & REFLOCK__REF_MASK; + + /* Verify that the lock was referenced and not already destroyed. */ + assert((state & REFLOCK__DESTROY_MASK) == REFLOCK__DESTROY); + + if (ref_count != 0) + reflock__await_event(reflock); + + state = InterlockedExchange(&reflock->state, REFLOCK__POISON); + assert(state == REFLOCK__DESTROY); +} + +#define SOCK__KNOWN_EPOLL_EVENTS \ + (EPOLLIN | EPOLLPRI | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLRDNORM | \ + EPOLLRDBAND | EPOLLWRNORM | EPOLLWRBAND | EPOLLMSG | EPOLLRDHUP) + +typedef enum sock__poll_status { + SOCK__POLL_IDLE = 0, + SOCK__POLL_PENDING, + SOCK__POLL_CANCELLED +} sock__poll_status_t; + +typedef struct sock_state { + IO_STATUS_BLOCK io_status_block; + AFD_POLL_INFO poll_info; + queue_node_t queue_node; + tree_node_t tree_node; + poll_group_t* poll_group; + SOCKET base_socket; + epoll_data_t user_data; + uint32_t user_events; + uint32_t pending_events; + sock__poll_status_t poll_status; + bool delete_pending; +} sock_state_t; + +static inline sock_state_t* sock__alloc(void) { + sock_state_t* sock_state = malloc(sizeof *sock_state); + if (sock_state == NULL) + return_set_error(NULL, ERROR_NOT_ENOUGH_MEMORY); + return sock_state; +} + +static inline void sock__free(sock_state_t* sock_state) { + assert(sock_state != NULL); + free(sock_state); +} + +static inline int sock__cancel_poll(sock_state_t* sock_state) { + assert(sock_state->poll_status == SOCK__POLL_PENDING); + + if (afd_cancel_poll(poll_group_get_afd_device_handle(sock_state->poll_group), + &sock_state->io_status_block) < 0) + return -1; + + sock_state->poll_status = SOCK__POLL_CANCELLED; + sock_state->pending_events = 0; + return 0; +} + +sock_state_t* sock_new(port_state_t* port_state, SOCKET socket) { + SOCKET base_socket; + poll_group_t* poll_group; + sock_state_t* sock_state; + + if (socket == 0 || socket == INVALID_SOCKET) + return_set_error(NULL, ERROR_INVALID_HANDLE); + + base_socket = ws_get_base_socket(socket); + if (base_socket == INVALID_SOCKET) + return NULL; + + poll_group = poll_group_acquire(port_state); + if (poll_group == NULL) + return NULL; + + sock_state = sock__alloc(); + if (sock_state == NULL) + goto err1; + + memset(sock_state, 0, sizeof *sock_state); + + sock_state->base_socket = base_socket; + sock_state->poll_group = poll_group; + + tree_node_init(&sock_state->tree_node); + queue_node_init(&sock_state->queue_node); + + if (port_register_socket(port_state, sock_state, socket) < 0) + goto err2; + + return sock_state; + +err2: + sock__free(sock_state); +err1: + poll_group_release(poll_group); + + return NULL; +} + +static int sock__delete(port_state_t* port_state, + sock_state_t* sock_state, + bool force) { + if (!sock_state->delete_pending) { + if (sock_state->poll_status == SOCK__POLL_PENDING) + sock__cancel_poll(sock_state); + + port_cancel_socket_update(port_state, sock_state); + port_unregister_socket(port_state, sock_state); + + sock_state->delete_pending = true; + } + + /* If the poll request still needs to complete, the sock_state object can't + * be free()d yet. `sock_feed_event()` or `port_close()` will take care + * of this later. */ + if (force || sock_state->poll_status == SOCK__POLL_IDLE) { + /* Free the sock_state now. */ + port_remove_deleted_socket(port_state, sock_state); + poll_group_release(sock_state->poll_group); + sock__free(sock_state); + } else { + /* Free the socket later. */ + port_add_deleted_socket(port_state, sock_state); + } + + return 0; +} + +void sock_delete(port_state_t* port_state, sock_state_t* sock_state) { + sock__delete(port_state, sock_state, false); +} + +void sock_force_delete(port_state_t* port_state, sock_state_t* sock_state) { + sock__delete(port_state, sock_state, true); +} + +int sock_set_event(port_state_t* port_state, + sock_state_t* sock_state, + const struct epoll_event* ev) { + /* EPOLLERR and EPOLLHUP are always reported, even when not requested by the + * caller. However they are disabled after a event has been reported for a + * socket for which the EPOLLONESHOT flag was set. */ + uint32_t events = ev->events | EPOLLERR | EPOLLHUP; + + sock_state->user_events = events; + sock_state->user_data = ev->data; + + if ((events & SOCK__KNOWN_EPOLL_EVENTS & ~sock_state->pending_events) != 0) + port_request_socket_update(port_state, sock_state); + + return 0; +} + +static inline DWORD sock__epoll_events_to_afd_events(uint32_t epoll_events) { + /* Always monitor for AFD_POLL_LOCAL_CLOSE, which is triggered when the + * socket is closed with closesocket() or CloseHandle(). */ + DWORD afd_events = AFD_POLL_LOCAL_CLOSE; + + if (epoll_events & (EPOLLIN | EPOLLRDNORM)) + afd_events |= AFD_POLL_RECEIVE | AFD_POLL_ACCEPT; + if (epoll_events & (EPOLLPRI | EPOLLRDBAND)) + afd_events |= AFD_POLL_RECEIVE_EXPEDITED; + if (epoll_events & (EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND)) + afd_events |= AFD_POLL_SEND; + if (epoll_events & (EPOLLIN | EPOLLRDNORM | EPOLLRDHUP)) + afd_events |= AFD_POLL_DISCONNECT; + if (epoll_events & EPOLLHUP) + afd_events |= AFD_POLL_ABORT; + if (epoll_events & EPOLLERR) + afd_events |= AFD_POLL_CONNECT_FAIL; + + return afd_events; +} + +static inline uint32_t sock__afd_events_to_epoll_events(DWORD afd_events) { + uint32_t epoll_events = 0; + + if (afd_events & (AFD_POLL_RECEIVE | AFD_POLL_ACCEPT)) + epoll_events |= EPOLLIN | EPOLLRDNORM; + if (afd_events & AFD_POLL_RECEIVE_EXPEDITED) + epoll_events |= EPOLLPRI | EPOLLRDBAND; + if (afd_events & AFD_POLL_SEND) + epoll_events |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND; + if (afd_events & AFD_POLL_DISCONNECT) + epoll_events |= EPOLLIN | EPOLLRDNORM | EPOLLRDHUP; + if (afd_events & AFD_POLL_ABORT) + epoll_events |= EPOLLHUP; + if (afd_events & AFD_POLL_CONNECT_FAIL) + /* Linux reports all these events after connect() has failed. */ + epoll_events |= + EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLRDNORM | EPOLLWRNORM | EPOLLRDHUP; + + return epoll_events; +} + +int sock_update(port_state_t* port_state, sock_state_t* sock_state) { + assert(!sock_state->delete_pending); + + if ((sock_state->poll_status == SOCK__POLL_PENDING) && + (sock_state->user_events & SOCK__KNOWN_EPOLL_EVENTS & + ~sock_state->pending_events) == 0) { + /* All the events the user is interested in are already being monitored by + * the pending poll operation. It might spuriously complete because of an + * event that we're no longer interested in; when that happens we'll submit + * a new poll operation with the updated event mask. */ + + } else if (sock_state->poll_status == SOCK__POLL_PENDING) { + /* A poll operation is already pending, but it's not monitoring for all the + * events that the user is interested in. Therefore, cancel the pending + * poll operation; when we receive it's completion package, a new poll + * operation will be submitted with the correct event mask. */ + if (sock__cancel_poll(sock_state) < 0) + return -1; + + } else if (sock_state->poll_status == SOCK__POLL_CANCELLED) { + /* The poll operation has already been cancelled, we're still waiting for + * it to return. For now, there's nothing that needs to be done. */ + + } else if (sock_state->poll_status == SOCK__POLL_IDLE) { + /* No poll operation is pending; start one. */ + sock_state->poll_info.Exclusive = FALSE; + sock_state->poll_info.NumberOfHandles = 1; + sock_state->poll_info.Timeout.QuadPart = INT64_MAX; + sock_state->poll_info.Handles[0].Handle = (HANDLE) sock_state->base_socket; + sock_state->poll_info.Handles[0].Status = 0; + sock_state->poll_info.Handles[0].Events = + sock__epoll_events_to_afd_events(sock_state->user_events); + + if (afd_poll(poll_group_get_afd_device_handle(sock_state->poll_group), + &sock_state->poll_info, + &sock_state->io_status_block) < 0) { + switch (GetLastError()) { + case ERROR_IO_PENDING: + /* Overlapped poll operation in progress; this is expected. */ + break; + case ERROR_INVALID_HANDLE: + /* Socket closed; it'll be dropped from the epoll set. */ + return sock__delete(port_state, sock_state, false); + default: + /* Other errors are propagated to the caller. */ + return_map_error(-1); + } + } + + /* The poll request was successfully submitted. */ + sock_state->poll_status = SOCK__POLL_PENDING; + sock_state->pending_events = sock_state->user_events; + + } else { + /* Unreachable. */ + assert(false); + } + + port_cancel_socket_update(port_state, sock_state); + return 0; +} + +int sock_feed_event(port_state_t* port_state, + IO_STATUS_BLOCK* io_status_block, + struct epoll_event* ev) { + sock_state_t* sock_state = + container_of(io_status_block, sock_state_t, io_status_block); + AFD_POLL_INFO* poll_info = &sock_state->poll_info; + uint32_t epoll_events = 0; + + sock_state->poll_status = SOCK__POLL_IDLE; + sock_state->pending_events = 0; + + if (sock_state->delete_pending) { + /* Socket has been deleted earlier and can now be freed. */ + return sock__delete(port_state, sock_state, false); + + } else if (io_status_block->Status == STATUS_CANCELLED) { + /* The poll request was cancelled by CancelIoEx. */ + + } else if (!NT_SUCCESS(io_status_block->Status)) { + /* The overlapped request itself failed in an unexpected way. */ + epoll_events = EPOLLERR; + + } else if (poll_info->NumberOfHandles < 1) { + /* This poll operation succeeded but didn't report any socket events. */ + + } else if (poll_info->Handles[0].Events & AFD_POLL_LOCAL_CLOSE) { + /* The poll operation reported that the socket was closed. */ + return sock__delete(port_state, sock_state, false); + + } else { + /* Events related to our socket were reported. */ + epoll_events = + sock__afd_events_to_epoll_events(poll_info->Handles[0].Events); + } + + /* Requeue the socket so a new poll request will be submitted. */ + port_request_socket_update(port_state, sock_state); + + /* Filter out events that the user didn't ask for. */ + epoll_events &= sock_state->user_events; + + /* Return if there are no epoll events to report. */ + if (epoll_events == 0) + return 0; + + /* If the the socket has the EPOLLONESHOT flag set, unmonitor all events, + * even EPOLLERR and EPOLLHUP. But always keep looking for closed sockets. */ + if (sock_state->user_events & EPOLLONESHOT) + sock_state->user_events = 0; + + ev->data = sock_state->user_data; + ev->events = epoll_events; + return 1; +} + +sock_state_t* sock_state_from_queue_node(queue_node_t* queue_node) { + return container_of(queue_node, sock_state_t, queue_node); +} + +queue_node_t* sock_state_to_queue_node(sock_state_t* sock_state) { + return &sock_state->queue_node; +} + +sock_state_t* sock_state_from_tree_node(tree_node_t* tree_node) { + return container_of(tree_node, sock_state_t, tree_node); +} + +tree_node_t* sock_state_to_tree_node(sock_state_t* sock_state) { + return &sock_state->tree_node; +} + +void ts_tree_init(ts_tree_t* ts_tree) { + tree_init(&ts_tree->tree); + InitializeSRWLock(&ts_tree->lock); +} + +void ts_tree_node_init(ts_tree_node_t* node) { + tree_node_init(&node->tree_node); + reflock_init(&node->reflock); +} + +int ts_tree_add(ts_tree_t* ts_tree, ts_tree_node_t* node, uintptr_t key) { + int r; + + AcquireSRWLockExclusive(&ts_tree->lock); + r = tree_add(&ts_tree->tree, &node->tree_node, key); + ReleaseSRWLockExclusive(&ts_tree->lock); + + return r; +} + +static inline ts_tree_node_t* ts_tree__find_node(ts_tree_t* ts_tree, + uintptr_t key) { + tree_node_t* tree_node = tree_find(&ts_tree->tree, key); + if (tree_node == NULL) + return NULL; + + return container_of(tree_node, ts_tree_node_t, tree_node); +} + +ts_tree_node_t* ts_tree_del_and_ref(ts_tree_t* ts_tree, uintptr_t key) { + ts_tree_node_t* ts_tree_node; + + AcquireSRWLockExclusive(&ts_tree->lock); + + ts_tree_node = ts_tree__find_node(ts_tree, key); + if (ts_tree_node != NULL) { + tree_del(&ts_tree->tree, &ts_tree_node->tree_node); + reflock_ref(&ts_tree_node->reflock); + } + + ReleaseSRWLockExclusive(&ts_tree->lock); + + return ts_tree_node; +} + +ts_tree_node_t* ts_tree_find_and_ref(ts_tree_t* ts_tree, uintptr_t key) { + ts_tree_node_t* ts_tree_node; + + AcquireSRWLockShared(&ts_tree->lock); + + ts_tree_node = ts_tree__find_node(ts_tree, key); + if (ts_tree_node != NULL) + reflock_ref(&ts_tree_node->reflock); + + ReleaseSRWLockShared(&ts_tree->lock); + + return ts_tree_node; +} + +void ts_tree_node_unref(ts_tree_node_t* node) { + reflock_unref(&node->reflock); +} + +void ts_tree_node_unref_and_destroy(ts_tree_node_t* node) { + reflock_unref_and_destroy(&node->reflock); +} + +void tree_init(tree_t* tree) { + memset(tree, 0, sizeof *tree); +} + +void tree_node_init(tree_node_t* node) { + memset(node, 0, sizeof *node); +} + +#define TREE__ROTATE(cis, trans) \ + tree_node_t* p = node; \ + tree_node_t* q = node->trans; \ + tree_node_t* parent = p->parent; \ + \ + if (parent) { \ + if (parent->left == p) \ + parent->left = q; \ + else \ + parent->right = q; \ + } else { \ + tree->root = q; \ + } \ + \ + q->parent = parent; \ + p->parent = q; \ + p->trans = q->cis; \ + if (p->trans) \ + p->trans->parent = p; \ + q->cis = p; + +static inline void tree__rotate_left(tree_t* tree, tree_node_t* node) { + TREE__ROTATE(left, right) +} + +static inline void tree__rotate_right(tree_t* tree, tree_node_t* node) { + TREE__ROTATE(right, left) +} + +#define TREE__INSERT_OR_DESCEND(side) \ + if (parent->side) { \ + parent = parent->side; \ + } else { \ + parent->side = node; \ + break; \ + } + +#define TREE__REBALANCE_AFTER_INSERT(cis, trans) \ + tree_node_t* grandparent = parent->parent; \ + tree_node_t* uncle = grandparent->trans; \ + \ + if (uncle && uncle->red) { \ + parent->red = uncle->red = false; \ + grandparent->red = true; \ + node = grandparent; \ + } else { \ + if (node == parent->trans) { \ + tree__rotate_##cis(tree, parent); \ + node = parent; \ + parent = node->parent; \ + } \ + parent->red = false; \ + grandparent->red = true; \ + tree__rotate_##trans(tree, grandparent); \ + } + +int tree_add(tree_t* tree, tree_node_t* node, uintptr_t key) { + tree_node_t* parent; + + parent = tree->root; + if (parent) { + for (;;) { + if (key < parent->key) { + TREE__INSERT_OR_DESCEND(left) + } else if (key > parent->key) { + TREE__INSERT_OR_DESCEND(right) + } else { + return -1; + } + } + } else { + tree->root = node; + } + + node->key = key; + node->left = node->right = NULL; + node->parent = parent; + node->red = true; + + for (; parent && parent->red; parent = node->parent) { + if (parent == parent->parent->left) { + TREE__REBALANCE_AFTER_INSERT(left, right) + } else { + TREE__REBALANCE_AFTER_INSERT(right, left) + } + } + tree->root->red = false; + + return 0; +} + +#define TREE__REBALANCE_AFTER_REMOVE(cis, trans) \ + tree_node_t* sibling = parent->trans; \ + \ + if (sibling->red) { \ + sibling->red = false; \ + parent->red = true; \ + tree__rotate_##cis(tree, parent); \ + sibling = parent->trans; \ + } \ + if ((sibling->left && sibling->left->red) || \ + (sibling->right && sibling->right->red)) { \ + if (!sibling->trans || !sibling->trans->red) { \ + sibling->cis->red = false; \ + sibling->red = true; \ + tree__rotate_##trans(tree, sibling); \ + sibling = parent->trans; \ + } \ + sibling->red = parent->red; \ + parent->red = sibling->trans->red = false; \ + tree__rotate_##cis(tree, parent); \ + node = tree->root; \ + break; \ + } \ + sibling->red = true; + +void tree_del(tree_t* tree, tree_node_t* node) { + tree_node_t* parent = node->parent; + tree_node_t* left = node->left; + tree_node_t* right = node->right; + tree_node_t* next; + bool red; + + if (!left) { + next = right; + } else if (!right) { + next = left; + } else { + next = right; + while (next->left) + next = next->left; + } + + if (parent) { + if (parent->left == node) + parent->left = next; + else + parent->right = next; + } else { + tree->root = next; + } + + if (left && right) { + red = next->red; + next->red = node->red; + next->left = left; + left->parent = next; + if (next != right) { + parent = next->parent; + next->parent = node->parent; + node = next->right; + parent->left = node; + next->right = right; + right->parent = next; + } else { + next->parent = parent; + parent = next; + node = next->right; + } + } else { + red = node->red; + node = next; + } + + if (node) + node->parent = parent; + if (red) + return; + if (node && node->red) { + node->red = false; + return; + } + + do { + if (node == tree->root) + break; + if (node == parent->left) { + TREE__REBALANCE_AFTER_REMOVE(left, right) + } else { + TREE__REBALANCE_AFTER_REMOVE(right, left) + } + node = parent; + parent = parent->parent; + } while (!node->red); + + if (node) + node->red = false; +} + +tree_node_t* tree_find(const tree_t* tree, uintptr_t key) { + tree_node_t* node = tree->root; + while (node) { + if (key < node->key) + node = node->left; + else if (key > node->key) + node = node->right; + else + return node; + } + return NULL; +} + +tree_node_t* tree_root(const tree_t* tree) { + return tree->root; +} + +#ifndef SIO_BSP_HANDLE_POLL +#define SIO_BSP_HANDLE_POLL 0x4800001D +#endif + +#ifndef SIO_BASE_HANDLE +#define SIO_BASE_HANDLE 0x48000022 +#endif + +int ws_global_init(void) { + int r; + WSADATA wsa_data; + + r = WSAStartup(MAKEWORD(2, 2), &wsa_data); + if (r != 0) + return_set_error(-1, (DWORD) r); + + return 0; +} + +static inline SOCKET ws__ioctl_get_bsp_socket(SOCKET socket, DWORD ioctl) { + SOCKET bsp_socket; + DWORD bytes; + + if (WSAIoctl(socket, + ioctl, + NULL, + 0, + &bsp_socket, + sizeof bsp_socket, + &bytes, + NULL, + NULL) != SOCKET_ERROR) + return bsp_socket; + else + return INVALID_SOCKET; +} + +SOCKET ws_get_base_socket(SOCKET socket) { + SOCKET base_socket; + DWORD error; + + for (;;) { + base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BASE_HANDLE); + if (base_socket != INVALID_SOCKET) + return base_socket; + + error = GetLastError(); + if (error == WSAENOTSOCK) + return_set_error(INVALID_SOCKET, error); + + /* Even though Microsoft documentation clearly states that LSPs should + * never intercept the `SIO_BASE_HANDLE` ioctl [1], Komodia based LSPs do + * so anyway, breaking it, with the apparent intention of preventing LSP + * bypass [2]. Fortunately they don't handle `SIO_BSP_HANDLE_POLL`, which + * will at least let us obtain the socket associated with the next winsock + * protocol chain entry. If this succeeds, loop around and call + * `SIO_BASE_HANDLE` again with the returned BSP socket, to make sure that + * we unwrap all layers and retrieve the actual base socket. + * [1] https://docs.microsoft.com/en-us/windows/win32/winsock/winsock-ioctls + * [2] https://www.komodia.com/newwiki/index.php?title=Komodia%27s_Redirector_bug_fixes#Version_2.2.2.6 + */ + base_socket = ws__ioctl_get_bsp_socket(socket, SIO_BSP_HANDLE_POLL); + if (base_socket != INVALID_SOCKET && base_socket != socket) + socket = base_socket; + else + return_set_error(INVALID_SOCKET, error); + } +} diff --git a/external/libhv/libhv-1.3.2/event/wepoll/wepoll.h b/external/libhv/libhv-1.3.2/event/wepoll/wepoll.h new file mode 100644 index 0000000..daf6bdb --- /dev/null +++ b/external/libhv/libhv-1.3.2/event/wepoll/wepoll.h @@ -0,0 +1,113 @@ +/* + * wepoll - epoll for Windows + * https://github.com/piscisaureus/wepoll + * + * Copyright 2012-2020, Bert Belder + * 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. + * + * 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 WEPOLL_H_ +#define WEPOLL_H_ + +#ifndef WEPOLL_EXPORT +#define WEPOLL_EXPORT +#endif + +#include + +enum EPOLL_EVENTS { + EPOLLIN = (int) (1U << 0), + EPOLLPRI = (int) (1U << 1), + EPOLLOUT = (int) (1U << 2), + EPOLLERR = (int) (1U << 3), + EPOLLHUP = (int) (1U << 4), + EPOLLRDNORM = (int) (1U << 6), + EPOLLRDBAND = (int) (1U << 7), + EPOLLWRNORM = (int) (1U << 8), + EPOLLWRBAND = (int) (1U << 9), + EPOLLMSG = (int) (1U << 10), /* Never reported. */ + EPOLLRDHUP = (int) (1U << 13), + EPOLLONESHOT = (int) (1U << 31) +}; + +#define EPOLLIN (1U << 0) +#define EPOLLPRI (1U << 1) +#define EPOLLOUT (1U << 2) +#define EPOLLERR (1U << 3) +#define EPOLLHUP (1U << 4) +#define EPOLLRDNORM (1U << 6) +#define EPOLLRDBAND (1U << 7) +#define EPOLLWRNORM (1U << 8) +#define EPOLLWRBAND (1U << 9) +#define EPOLLMSG (1U << 10) +#define EPOLLRDHUP (1U << 13) +#define EPOLLONESHOT (1U << 31) + +#define EPOLL_CTL_ADD 1 +#define EPOLL_CTL_MOD 2 +#define EPOLL_CTL_DEL 3 + +typedef void* HANDLE; +typedef uintptr_t SOCKET; + +typedef union epoll_data { + void* ptr; + int fd; + uint32_t u32; + uint64_t u64; + SOCKET sock; /* Windows specific */ + HANDLE hnd; /* Windows specific */ +} epoll_data_t; + +struct epoll_event { + uint32_t events; /* Epoll events and flags */ + epoll_data_t data; /* User data variable */ +}; + +#ifdef __cplusplus +extern "C" { +#endif + +WEPOLL_EXPORT HANDLE epoll_create(int size); +WEPOLL_EXPORT HANDLE epoll_create1(int flags); + +WEPOLL_EXPORT int epoll_close(HANDLE ephnd); + +WEPOLL_EXPORT int epoll_ctl(HANDLE ephnd, + int op, + SOCKET sock, + struct epoll_event* event); + +WEPOLL_EXPORT int epoll_wait(HANDLE ephnd, + struct epoll_event* events, + int maxevents, + int timeout); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* WEPOLL_H_ */ diff --git a/external/libhv/libhv-1.3.2/evpp/Buffer.h b/external/libhv/libhv-1.3.2/evpp/Buffer.h new file mode 100644 index 0000000..1f6644f --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/Buffer.h @@ -0,0 +1,15 @@ +#ifndef HV_BUFFER_HPP_ +#define HV_BUFFER_HPP_ + +#include + +#include "hbuf.h" + +namespace hv { + +typedef HBuf Buffer; +typedef std::shared_ptr BufferPtr; + +} + +#endif // HV_BUFFER_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/Channel.h b/external/libhv/libhv-1.3.2/evpp/Channel.h new file mode 100644 index 0000000..faab81e --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/Channel.h @@ -0,0 +1,375 @@ +#ifndef HV_CHANNEL_HPP_ +#define HV_CHANNEL_HPP_ + +#include +#include +#include + +#include "hloop.h" +#include "hsocket.h" + +#include "Buffer.h" + +namespace hv { + +class Channel { +public: + Channel(hio_t* io = NULL) { + io_ = io; + fd_ = -1; + id_ = 0; + ctx_ = NULL; + status = CLOSED; + if (io) { + fd_ = hio_fd(io); + id_ = hio_id(io); + ctx_ = hio_context(io); + hio_set_context(io, this); + if (hio_is_opened(io)) { + status = OPENED; + } + if (hio_getcb_read(io) == NULL) { + hio_setcb_read(io_, on_read); + } + if (hio_getcb_write(io) == NULL) { + hio_setcb_write(io_, on_write); + } + if (hio_getcb_close(io) == NULL) { + hio_setcb_close(io_, on_close); + } + } + } + + virtual ~Channel() { + if (isOpened()) { + close(); + // NOTE: Detach after destructor to avoid triggering onclose + if (io_ && id_ == hio_id(io_)) { + hio_set_context(io_, NULL); + } + } + } + + hio_t* io() { return io_; } + int fd() { return fd_; } + uint32_t id() { return id_; } + int error() { return hio_error(io_); } + + // context + void* context() { + return ctx_; + } + void setContext(void* ctx) { + ctx_ = ctx; + } + template + T* newContext() { + ctx_ = new T; + return (T*)ctx_; + } + template + T* getContext() { + return (T*)ctx_; + } + template + void deleteContext() { + if (ctx_) { + delete (T*)ctx_; + ctx_ = NULL; + } + } + + // contextPtr + std::shared_ptr contextPtr() { + return contextPtr_; + } + void setContextPtr(const std::shared_ptr& ctx) { + contextPtr_ = ctx; + } + void setContextPtr(std::shared_ptr&& ctx) { + contextPtr_ = std::move(ctx); + } + template + std::shared_ptr newContextPtr() { + contextPtr_ = std::make_shared(); + return std::static_pointer_cast(contextPtr_); + } + template + std::shared_ptr getContextPtr() { + return std::static_pointer_cast(contextPtr_); + } + void deleteContextPtr() { + contextPtr_.reset(); + } + + bool isOpened() { + if (io_ == NULL || status >= DISCONNECTED) return false; + return id_ == hio_id(io_) && hio_is_opened(io_); + } + bool isClosed() { + return !isOpened(); + } + + int startRead() { + if (!isOpened()) return -1; + return hio_read_start(io_); + } + + int stopRead() { + if (!isOpened()) return -1; + return hio_read_stop(io_); + } + + int readOnce() { + if (!isOpened()) return -1; + return hio_read_once(io_); + } + + int readString() { + if (!isOpened()) return -1; + return hio_readstring(io_); + } + + int readLine() { + if (!isOpened()) return -1; + return hio_readline(io_); + } + + int readBytes(int len) { + if (!isOpened() || len <= 0) return -1; + return hio_readbytes(io_, len); + } + + // write thread-safe + int write(const void* data, int size) { + if (!isOpened()) return -1; + return hio_write(io_, data, size); + } + + int write(Buffer* buf) { + return write(buf->data(), buf->size()); + } + + int write(const std::string& str) { + return write(str.data(), str.size()); + } + + // iobuf setting + void setReadBuf(void* buf, size_t len) { + if (io_ == NULL) return; + hio_set_readbuf(io_, buf, len); + } + void setMaxReadBufsize(uint32_t size) { + if (io_ == NULL) return; + hio_set_max_read_bufsize(io_, size); + } + void setMaxWriteBufsize(uint32_t size) { + if (io_ == NULL) return; + hio_set_max_write_bufsize(io_, size); + } + size_t writeBufsize() { + if (io_ == NULL) return 0; + return hio_write_bufsize(io_); + } + bool isWriteComplete() { + return writeBufsize() == 0; + } + + // close thread-safe + int close(bool async = false) { + if (isClosed()) return -1; + status = CLOSED; + return async ? hio_close_async(io_) : hio_close(io_); + } + +public: + hio_t* io_; + int fd_; + uint32_t id_; + void* ctx_; + enum Status { + OPENED, + CONNECTING, + CONNECTED, + DISCONNECTED, + CLOSED, + } status; + std::function onread; + // NOTE: Use Channel::isWriteComplete in onwrite callback to determine whether all data has been written. + std::function onwrite; + std::function onclose; + std::shared_ptr contextPtr_; + +private: + static void on_read(hio_t* io, void* data, int readbytes) { + Channel* channel = (Channel*)hio_context(io); + if (channel && channel->onread) { + Buffer buf(data, readbytes); + channel->onread(&buf); + } + } + + static void on_write(hio_t* io, const void* data, int writebytes) { + Channel* channel = (Channel*)hio_context(io); + if (channel && channel->onwrite) { + Buffer buf((void*)data, writebytes); + channel->onwrite(&buf); + } + } + + static void on_close(hio_t* io) { + Channel* channel = (Channel*)hio_context(io); + if (channel) { + channel->status = CLOSED; + if (channel->onclose) { + channel->onclose(); + } + } + } +}; + +class SocketChannel : public Channel { +public: + std::function onconnect; // only for TcpClient + std::function heartbeat; + + SocketChannel(hio_t* io) : Channel(io) { + } + virtual ~SocketChannel() {} + + // SSL/TLS + int enableSSL() { + if (io_ == NULL) return -1; + return hio_enable_ssl(io_); + } + bool isSSL() { + if (io_ == NULL) return false; + return hio_is_ssl(io_); + } + int setSSL(hssl_t ssl) { + if (io_ == NULL) return -1; + return hio_set_ssl(io_, ssl); + } + int setSslCtx(hssl_ctx_t ssl_ctx) { + if (io_ == NULL) return -1; + return hio_set_ssl_ctx(io_, ssl_ctx); + } + int newSslCtx(hssl_ctx_opt_t* opt) { + if (io_ == NULL) return -1; + return hio_new_ssl_ctx(io_, opt); + } + // for hssl_set_sni_hostname + int setHostname(const std::string& hostname) { + if (io_ == NULL) return -1; + return hio_set_hostname(io_, hostname.c_str()); + } + + // timeout + void setConnectTimeout(int timeout_ms) { + if (io_ == NULL) return; + hio_set_connect_timeout(io_, timeout_ms); + } + void setCloseTimeout(int timeout_ms) { + if (io_ == NULL) return; + hio_set_close_timeout(io_, timeout_ms); + } + void setReadTimeout(int timeout_ms) { + if (io_ == NULL) return; + hio_set_read_timeout(io_, timeout_ms); + } + void setWriteTimeout(int timeout_ms) { + if (io_ == NULL) return; + hio_set_write_timeout(io_, timeout_ms); + } + void setKeepaliveTimeout(int timeout_ms) { + if (io_ == NULL) return; + hio_set_keepalive_timeout(io_, timeout_ms); + } + + // heartbeat + // NOTE: Beware of circular reference problems caused by passing SocketChannelPtr by value. + void setHeartbeat(int interval_ms, std::function fn) { + if (io_ == NULL) return; + heartbeat = std::move(fn); + hio_set_heartbeat(io_, interval_ms, send_heartbeat); + } + + /* + * unpack + * + * NOTE: unpack_setting_t of multiple IOs of the same function also are same, + * so only the pointer of unpack_setting_t is stored in hio_t, + * the life time of unpack_setting_t shoud be guaranteed by caller. + */ + void setUnpack(unpack_setting_t* setting) { + if (io_ == NULL) return; + hio_set_unpack(io_, setting); + } + + int startConnect(int port, const char* host = "127.0.0.1") { + sockaddr_u peeraddr; + memset(&peeraddr, 0, sizeof(peeraddr)); + int ret = sockaddr_set_ipport(&peeraddr, host, port); + if (ret != 0) { + // hloge("unknown host %s", host); + return ret; + } + return startConnect(&peeraddr.sa); + } + + int startConnect(struct sockaddr* peeraddr) { + if (io_ == NULL) return -1; + hio_set_peeraddr(io_, peeraddr, SOCKADDR_LEN(peeraddr)); + return startConnect(); + } + + int startConnect() { + if (io_ == NULL) return -1; + status = CONNECTING; + hio_setcb_connect(io_, on_connect); + return hio_connect(io_); + } + + bool isConnected() { + return status == CONNECTED && isOpened(); + } + + std::string localaddr() { + if (io_ == NULL) return ""; + struct sockaddr* addr = hio_localaddr(io_); + char buf[SOCKADDR_STRLEN] = {0}; + return SOCKADDR_STR(addr, buf); + } + + std::string peeraddr() { + if (io_ == NULL) return ""; + struct sockaddr* addr = hio_peeraddr(io_); + char buf[SOCKADDR_STRLEN] = {0}; + return SOCKADDR_STR(addr, buf); + } + +private: + static void on_connect(hio_t* io) { + SocketChannel* channel = (SocketChannel*)hio_context(io); + if (channel) { + channel->status = CONNECTED; + if (channel->onconnect) { + channel->onconnect(); + } + } + } + + static void send_heartbeat(hio_t* io) { + SocketChannel* channel = (SocketChannel*)hio_context(io); + if (channel && channel->heartbeat) { + channel->heartbeat(); + } + } +}; + +typedef std::shared_ptr ChannelPtr; +typedef std::shared_ptr SocketChannelPtr; + +} + +#endif // HV_CHANNEL_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/Event.h b/external/libhv/libhv-1.3.2/evpp/Event.h new file mode 100644 index 0000000..44d0c7e --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/Event.h @@ -0,0 +1,47 @@ +#ifndef HV_EVENT_HPP_ +#define HV_EVENT_HPP_ + +#include +#include + +#include "hloop.h" + +namespace hv { + +struct Event; +struct Timer; + +typedef uint64_t TimerID; +#define INVALID_TIMER_ID ((hv::TimerID)-1) + +typedef std::function EventCallback; +typedef std::function TimerCallback; + +struct Event { + hevent_t event; + EventCallback cb; + + Event(EventCallback cb = NULL) { + memset(&event, 0, sizeof(hevent_t)); + this->cb = std::move(cb); + } +}; + +struct Timer { + htimer_t* timer; + TimerCallback cb; + uint32_t repeat; + + Timer(htimer_t* timer = NULL, TimerCallback cb = NULL, uint32_t repeat = INFINITE) { + this->timer = timer; + this->cb = std::move(cb); + this->repeat = repeat; + } +}; + +typedef std::shared_ptr EventPtr; +typedef std::shared_ptr TimerPtr; + +} + +#endif // HV_EVENT_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoop.h b/external/libhv/libhv-1.3.2/evpp/EventLoop.h new file mode 100644 index 0000000..cce835f --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoop.h @@ -0,0 +1,277 @@ +#ifndef HV_EVENT_LOOP_HPP_ +#define HV_EVENT_LOOP_HPP_ + +#include +#include +#include +#include + +#include "hloop.h" +#include "hthread.h" + +#include "Status.h" +#include "Event.h" +#include "ThreadLocalStorage.h" + +namespace hv { + +class EventLoop : public Status { +public: + + typedef std::function Functor; + + // New an EventLoop using an existing hloop_t object, + // so we can embed an EventLoop object into the old application based on hloop. + // NOTE: Be careful to deal with destroy of hloop_t. + EventLoop(hloop_t* loop = NULL) { + setStatus(kInitializing); + if (loop) { + loop_ = loop; + is_loop_owner = false; + } else { + loop_ = hloop_new(HLOOP_FLAG_AUTO_FREE); + is_loop_owner = true; + } + connectionNum = 0; + nextTimerID = 0; + setStatus(kInitialized); + } + + ~EventLoop() { + stop(); + } + + hloop_t* loop() { + return loop_; + } + + // @brief Run loop forever + void run() { + if (loop_ == NULL) return; + if (status() == kRunning) return; + ThreadLocalStorage::set(ThreadLocalStorage::EVENT_LOOP, this); + setStatus(kRunning); + hloop_run(loop_); + setStatus(kStopped); + } + + // stop thread-safe + void stop() { + if (loop_ == NULL) return; + if (status() < kRunning) { + if (is_loop_owner) { + hloop_free(&loop_); + } + loop_ = NULL; + return; + } + setStatus(kStopping); + hloop_stop(loop_); + loop_ = NULL; + } + + void pause() { + if (loop_ == NULL) return; + if (isRunning()) { + hloop_pause(loop_); + setStatus(kPause); + } + } + + void resume() { + if (loop_ == NULL) return; + if (isPause()) { + hloop_resume(loop_); + setStatus(kRunning); + } + } + + // Timer interfaces: setTimer, killTimer, resetTimer + TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) { + assertInLoopThread(); + if (loop_ == NULL) return INVALID_TIMER_ID; + htimer_t* htimer = htimer_add(loop_, onTimer, timeout_ms, repeat); + assert(htimer != NULL); + if (timerID == INVALID_TIMER_ID) { + timerID = generateTimerID(); + } + hevent_set_id(htimer, timerID); + hevent_set_userdata(htimer, this); + + timers[timerID] = std::make_shared(htimer, cb, repeat); + return timerID; + } + + // setTimerInLoop thread-safe + TimerID setTimerInLoop(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE, TimerID timerID = INVALID_TIMER_ID) { + if (timerID == INVALID_TIMER_ID) { + timerID = generateTimerID(); + } + runInLoop(std::bind(&EventLoop::setTimer, this, timeout_ms, cb, repeat, timerID)); + return timerID; + } + + // alias javascript setTimeout, setInterval + // setTimeout thread-safe + TimerID setTimeout(int timeout_ms, TimerCallback cb) { + return setTimerInLoop(timeout_ms, cb, 1); + } + // setInterval thread-safe + TimerID setInterval(int interval_ms, TimerCallback cb) { + return setTimerInLoop(interval_ms, cb, INFINITE); + } + + // killTimer thread-safe + void killTimer(TimerID timerID) { + runInLoop([timerID, this](){ + auto iter = timers.find(timerID); + if (iter != timers.end()) { + htimer_del(iter->second->timer); + timers.erase(iter); + } + }); + } + + // resetTimer thread-safe + void resetTimer(TimerID timerID, int timeout_ms = 0) { + runInLoop([timerID, timeout_ms, this](){ + auto iter = timers.find(timerID); + if (iter != timers.end()) { + htimer_reset(iter->second->timer, timeout_ms); + if (iter->second->repeat == 0) { + iter->second->repeat = 1; + } + } + }); + } + + long tid() { + if (loop_ == NULL) return hv_gettid(); + return hloop_tid(loop_); + } + + bool isInLoopThread() { + if (loop_ == NULL) return false; + return hv_gettid() == hloop_tid(loop_); + } + + void assertInLoopThread() { + assert(isInLoopThread()); + } + + void runInLoop(Functor fn) { + if (isRunning() && isInLoopThread()) { + if (fn) fn(); + } else { + queueInLoop(std::move(fn)); + } + } + + void queueInLoop(Functor fn) { + postEvent([fn](Event* ev) { + if (fn) fn(); + }); + } + + void postEvent(EventCallback cb) { + if (loop_ == NULL) return; + + EventPtr ev = std::make_shared(cb); + hevent_set_userdata(&ev->event, this); + ev->event.cb = onCustomEvent; + + mutex_.lock(); + customEvents.push(ev); + mutex_.unlock(); + + hloop_post_event(loop_, &ev->event); + } + +private: + TimerID generateTimerID() { + return (((TimerID)tid() & 0xFFFFFFFF) << 32) | ++nextTimerID; + } + + static void onTimer(htimer_t* htimer) { + EventLoop* loop = (EventLoop*)hevent_userdata(htimer); + + TimerID timerID = hevent_id(htimer); + TimerPtr timer = NULL; + + auto iter = loop->timers.find(timerID); + if (iter != loop->timers.end()) { + timer = iter->second; + if (timer->repeat != INFINITE) --timer->repeat; + } + + if (timer) { + if (timer->cb) timer->cb(timerID); + if (timer->repeat == 0) { + // htimer_t alloc and free by hloop, but timers[timerID] managed by EventLoop. + loop->timers.erase(timerID); + } + } + } + + static void onCustomEvent(hevent_t* hev) { + EventLoop* loop = (EventLoop*)hevent_userdata(hev); + + loop->mutex_.lock(); + EventPtr ev = loop->customEvents.front(); + loop->customEvents.pop(); + loop->mutex_.unlock(); + + if (ev && ev->cb) ev->cb(ev.get()); + } + +public: + std::atomic connectionNum; // for LB_LeastConnections +private: + hloop_t* loop_; + bool is_loop_owner; + std::mutex mutex_; + std::queue customEvents; // GUAREDE_BY(mutex_) + std::map timers; + std::atomic nextTimerID; +}; + +typedef std::shared_ptr EventLoopPtr; + +// ThreadLocalStorage +static inline EventLoop* tlsEventLoop() { + return (EventLoop*)ThreadLocalStorage::get(ThreadLocalStorage::EVENT_LOOP); +} +#define currentThreadEventLoop tlsEventLoop() + +static inline TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) { + EventLoop* loop = tlsEventLoop(); + assert(loop != NULL); + if (loop == NULL) return INVALID_TIMER_ID; + return loop->setTimer(timeout_ms, cb, repeat); +} + +static inline void killTimer(TimerID timerID) { + EventLoop* loop = tlsEventLoop(); + assert(loop != NULL); + if (loop == NULL) return; + loop->killTimer(timerID); +} + +static inline void resetTimer(TimerID timerID, int timeout_ms) { + EventLoop* loop = tlsEventLoop(); + assert(loop != NULL); + if (loop == NULL) return; + loop->resetTimer(timerID, timeout_ms); +} + +static inline TimerID setTimeout(int timeout_ms, TimerCallback cb) { + return setTimer(timeout_ms, cb, 1); +} + +static inline TimerID setInterval(int interval_ms, TimerCallback cb) { + return setTimer(interval_ms, cb, INFINITE); +} + +} + +#endif // HV_EVENT_LOOP_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoopThread.h b/external/libhv/libhv-1.3.2/evpp/EventLoopThread.h new file mode 100644 index 0000000..47f20db --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoopThread.h @@ -0,0 +1,115 @@ +#ifndef HV_EVENT_LOOP_THREAD_HPP_ +#define HV_EVENT_LOOP_THREAD_HPP_ + +#include + +#include "hlog.h" + +#include "EventLoop.h" + +namespace hv { + +class EventLoopThread : public Status { +public: + // Return 0 means OK, other failed. + typedef std::function Functor; + + EventLoopThread(EventLoopPtr loop = NULL) { + setStatus(kInitializing); + loop_ = loop ? loop : std::make_shared(); + setStatus(kInitialized); + } + + ~EventLoopThread() { + stop(); + join(); + } + + const EventLoopPtr& loop() { + return loop_; + } + + hloop_t* hloop() { + return loop_->loop(); + } + + bool isRunning() { + return loop_->isRunning(); + } + + // @param wait_thread_started: if ture this method will block until loop_thread started. + // @param pre: This functor will be executed when loop_thread started. + // @param post:This Functor will be executed when loop_thread stopped. + void start(bool wait_thread_started = true, + Functor pre = Functor(), + Functor post = Functor()) { + if (status() >= kStarting && status() < kStopped) return; + setStatus(kStarting); + + thread_ = std::make_shared(&EventLoopThread::loop_thread, this, pre, post); + + if (wait_thread_started) { + while (loop_->status() < kRunning) { + hv_delay(1); + } + } + } + + // @param wait_thread_started: if ture this method will block until loop_thread stopped. + // stop thread-safe + void stop(bool wait_thread_stopped = false) { + if (status() < kStarting || status() >= kStopping) return; + setStatus(kStopping); + + long loop_tid = loop_->tid(); + loop_->stop(); + + if (wait_thread_stopped) { + if (hv_gettid() == loop_tid) return; + join(); + } + } + + // @brief join loop_thread + // @note destructor will join loop_thread if you forget to call this method. + void join() { + if (thread_ && thread_->joinable()) { + thread_->join(); + thread_ = NULL; + } + } + +private: + void loop_thread(const Functor& pre, const Functor& post) { + hlogi("EventLoopThread started, tid=%ld", hv_gettid()); + setStatus(kStarted); + + if (pre) { + loop_->queueInLoop([this, pre]{ + if (pre() != 0) { + loop_->stop(); + } + }); + } + + loop_->run(); + assert(loop_->isStopped()); + + if (post) { + post(); + } + + setStatus(kStopped); + hlogi("EventLoopThread stopped, tid=%ld", hv_gettid()); + } + +private: + EventLoopPtr loop_; + std::shared_ptr thread_; +}; + +typedef std::shared_ptr EventLoopThreadPtr; + +} + +#endif // HV_EVENT_LOOP_THREAD_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool.h b/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool.h new file mode 100644 index 0000000..efdb317 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool.h @@ -0,0 +1,138 @@ +#ifndef HV_EVENT_LOOP_THREAD_POOL_HPP_ +#define HV_EVENT_LOOP_THREAD_POOL_HPP_ + +#include "EventLoopThread.h" +#include "hbase.h" + +namespace hv { + +class EventLoopThreadPool : public Status { +public: + EventLoopThreadPool(int thread_num = std::thread::hardware_concurrency()) { + setStatus(kInitializing); + thread_num_ = thread_num; + next_loop_idx_ = 0; + setStatus(kInitialized); + } + + ~EventLoopThreadPool() { + stop(); + join(); + } + + int threadNum() { + return thread_num_; + } + + void setThreadNum(int num) { + thread_num_ = num; + } + + EventLoopPtr nextLoop(load_balance_e lb = LB_RoundRobin) { + size_t numLoops = loop_threads_.size(); + if (numLoops == 0) return NULL; + size_t idx = 0; + if (lb == LB_RoundRobin) { + if (++next_loop_idx_ >= numLoops) next_loop_idx_ = 0; + idx = next_loop_idx_ % numLoops; + } else if (lb == LB_Random) { + idx = hv_rand(0, numLoops - 1); + } else if (lb == LB_LeastConnections) { + for (size_t i = 1; i < numLoops; ++i) { + if (loop_threads_[i]->loop()->connectionNum < loop_threads_[idx]->loop()->connectionNum) { + idx = i; + } + } + } else { + // Not Implemented + } + return loop_threads_[idx]->loop(); + } + + EventLoopPtr loop(int idx = -1) { + if (idx >= 0 && idx < (int)loop_threads_.size()) { + return loop_threads_[idx]->loop(); + } + return nextLoop(); + } + + hloop_t* hloop(int idx = -1) { + EventLoopPtr ptr = loop(idx); + return ptr ? ptr->loop() : NULL; + } + + // @param wait_threads_started: if ture this method will block until all loop_threads started. + // @param pre: This functor will be executed when loop_thread started. + // @param post:This Functor will be executed when loop_thread stopped. + void start(bool wait_threads_started = false, + std::function pre = NULL, + std::function post = NULL) { + if (thread_num_ == 0) return; + if (status() >= kStarting && status() < kStopped) return; + setStatus(kStarting); + + auto started_cnt = std::make_shared>(0); + auto exited_cnt = std::make_shared>(0); + + loop_threads_.clear(); + for (int i = 0; i < thread_num_; ++i) { + auto loop_thread = std::make_shared(); + const EventLoopPtr& loop = loop_thread->loop(); + loop_thread->start(false, + [this, started_cnt, pre, &loop]() { + if (++(*started_cnt) == thread_num_) { + setStatus(kRunning); + } + if (pre) pre(loop); + return 0; + }, + [this, exited_cnt, post, &loop]() { + if (post) post(loop); + if (++(*exited_cnt) == thread_num_) { + setStatus(kStopped); + } + return 0; + } + ); + loop_threads_.push_back(loop_thread); + } + + if (wait_threads_started) { + while (status() < kRunning) { + hv_delay(1); + } + } + } + + // @param wait_threads_started: if ture this method will block until all loop_threads stopped. + // stop thread-safe + void stop(bool wait_threads_stopped = false) { + if (status() < kStarting || status() >= kStopping) return; + setStatus(kStopping); + + for (auto& loop_thread : loop_threads_) { + loop_thread->stop(false); + } + + if (wait_threads_stopped) { + join(); + } + } + + // @brief join all loop_threads + // @note destructor will join loop_threads if you forget to call this method. + void join() { + for (auto& loop_thread : loop_threads_) { + loop_thread->join(); + } + } + +private: + int thread_num_; + std::vector loop_threads_; + std::atomic next_loop_idx_; +}; + +} + +#endif // HV_EVENT_LOOP_THREAD_POOL_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool_test.cpp b/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool_test.cpp new file mode 100644 index 0000000..a6fc9a3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoopThreadPool_test.cpp @@ -0,0 +1,55 @@ +/* + * EventLoopThreadPool_test.cpp + * + * @build: make evpp + * + */ + +#include "hv.h" + +#include "EventLoopThreadPool.h" + +using namespace hv; + +static void onTimer(TimerID timerID, int n) { + printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); +} + +int main(int argc, char* argv[]) { + HV_MEMCHECK; + hlog_set_level(LOG_LEVEL_DEBUG); + + printf("main tid=%ld\n", hv_gettid()); + + EventLoopThreadPool loop_threads(4); + loop_threads.start(true); + + int thread_num = loop_threads.threadNum(); + for (int i = 0; i < thread_num; ++i) { + EventLoopPtr loop = loop_threads.nextLoop(); + printf("worker[%d] tid=%ld\n", i, loop->tid()); + + loop->runInLoop([loop](){ + // runEvery 1s + loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); + }); + + loop->queueInLoop([](){ + printf("queueInLoop tid=%ld\n", hv_gettid()); + }); + + loop->runInLoop([](){ + printf("runInLoop tid=%ld\n", hv_gettid()); + }); + } + + // runAfter 10s + loop_threads.loop()->setTimeout(10000, [&loop_threads](TimerID timerID){ + loop_threads.stop(false); + }); + + // wait loop_threads exit + loop_threads.join(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoopThread_test.cpp b/external/libhv/libhv-1.3.2/evpp/EventLoopThread_test.cpp new file mode 100644 index 0000000..b8ab220 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoopThread_test.cpp @@ -0,0 +1,48 @@ +/* + * EventLoopThread_test.cpp + * + * @build: make evpp + * + */ + +#include "hv.h" + +#include "EventLoopThread.h" + +using namespace hv; + +static void onTimer(TimerID timerID, int n) { + printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); +} + +int main(int argc, char* argv[]) { + HV_MEMCHECK; + + printf("main tid=%ld\n", hv_gettid()); + + EventLoopThread loop_thread; + const EventLoopPtr& loop = loop_thread.loop(); + + // runEvery 1s + loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); + + // runAfter 10s + loop->setTimeout(10000, [&loop](TimerID timerID){ + loop->stop(); + }); + + loop_thread.start(); + + loop->queueInLoop([](){ + printf("queueInLoop tid=%ld\n", hv_gettid()); + }); + + loop->runInLoop([](){ + printf("runInLoop tid=%ld\n", hv_gettid()); + }); + + // wait loop_thread exit + loop_thread.join(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/EventLoop_test.cpp b/external/libhv/libhv-1.3.2/evpp/EventLoop_test.cpp new file mode 100644 index 0000000..a6d855c --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/EventLoop_test.cpp @@ -0,0 +1,45 @@ +/* + * EventLoop_test.cpp + * + * @build: make evpp + * + */ + +#include "hv.h" + +#include "EventLoop.h" + +using namespace hv; + +static void onTimer(TimerID timerID, int n) { + printf("tid=%ld timerID=%lu time=%lus n=%d\n", hv_gettid(), (unsigned long)timerID, (unsigned long)time(NULL), n); +} + +int main(int argc, char* argv[]) { + HV_MEMCHECK; + + printf("main tid=%ld\n", hv_gettid()); + + auto loop = std::make_shared(); + + // runEvery 1s + loop->setInterval(1000, std::bind(onTimer, std::placeholders::_1, 100)); + + // runAfter 10s + loop->setTimeout(10000, [&loop](TimerID timerID){ + loop->stop(); + }); + + loop->queueInLoop([](){ + printf("queueInLoop tid=%ld\n", hv_gettid()); + }); + + loop->runInLoop([](){ + printf("runInLoop tid=%ld\n", hv_gettid()); + }); + + // run until loop stopped + loop->run(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/README.md b/external/libhv/libhv-1.3.2/evpp/README.md new file mode 100644 index 0000000..cac9ad9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/README.md @@ -0,0 +1,24 @@ +The evpp module is designed to be header-only and does not participate in compilation. +hloop.h is encapsulated into c++ classes, referring to muduo and evpp. +You can modify and use evpp classes according to your own business. + +evpp模块被设计成只包含头文件,不参与编译。 +hloop.h中的c接口被封装成了c++的类,参考了muduo和evpp。 +你能修改和使用这些类根据你自己的业务。 + +## 目录结构 + +``` +. +├── Buffer.h 缓存类 +├── Channel.h 通道类,封装了hio_t +├── Event.h 事件类,封装了hevent_t、htimer_t +├── EventLoop.h 事件循环类,封装了hloop_t +├── EventLoopThread.h 事件循环线程类,组合了EventLoop和thread +├── EventLoopThreadPool.h 事件循环线程池类,组合了EventLoop和ThreadPool +├── TcpClient.h TCP客户端类 +├── TcpServer.h TCP服务端类 +├── UdpClient.h UDP客户端类 +└── UdpServer.h UDP服务端类 + +``` diff --git a/external/libhv/libhv-1.3.2/evpp/Status.h b/external/libhv/libhv-1.3.2/evpp/Status.h new file mode 100644 index 0000000..caf2853 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/Status.h @@ -0,0 +1,56 @@ +#ifndef HV_STATUS_HPP_ +#define HV_STATUS_HPP_ + +#include + +namespace hv { + +class Status { +public: + enum KStatus { + kNull = 0, + kInitializing = 1, + kInitialized = 2, + kStarting = 3, + kStarted = 4, + kRunning = 5, + kPause = 6, + kStopping = 7, + kStopped = 8, + kDestroyed = 9, + }; + + Status() { + status_ = kNull; + } + ~Status() { + status_ = kDestroyed; + } + + KStatus status() { + return status_; + } + + void setStatus(KStatus status) { + status_ = status; + } + + bool isRunning() { + return status_ == kRunning; + } + + bool isPause() { + return status_ == kPause; + } + + bool isStopped() { + return status_ == kStopped; + } + +private: + std::atomic status_; +}; + +} + +#endif // HV_STATUS_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/TcpClient.h b/external/libhv/libhv-1.3.2/evpp/TcpClient.h new file mode 100644 index 0000000..bcdea64 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TcpClient.h @@ -0,0 +1,301 @@ +#ifndef HV_TCP_CLIENT_HPP_ +#define HV_TCP_CLIENT_HPP_ + +#include "hsocket.h" +#include "hssl.h" +#include "hlog.h" + +#include "EventLoopThread.h" +#include "Channel.h" + +namespace hv { + +template +class TcpClientEventLoopTmpl { +public: + typedef std::shared_ptr TSocketChannelPtr; + + TcpClientEventLoopTmpl(EventLoopPtr loop = NULL) { + loop_ = loop ? loop : std::make_shared(); + remote_port = 0; + connect_timeout = HIO_DEFAULT_CONNECT_TIMEOUT; + tls = false; + tls_setting = NULL; + reconn_setting = NULL; + unpack_setting = NULL; + } + + virtual ~TcpClientEventLoopTmpl() { + HV_FREE(tls_setting); + HV_FREE(reconn_setting); + HV_FREE(unpack_setting); + } + + const EventLoopPtr& loop() { + return loop_; + } + + // NOTE: By default, not bind local port. If necessary, you can call bind() after createsocket(). + // @retval >=0 connfd, <0 error + int createsocket(int remote_port, const char* remote_host = "127.0.0.1") { + memset(&remote_addr, 0, sizeof(remote_addr)); + int ret = sockaddr_set_ipport(&remote_addr, remote_host, remote_port); + if (ret != 0) { + return NABS(ret); + } + this->remote_host = remote_host; + this->remote_port = remote_port; + return createsocket(&remote_addr.sa); + } + + int createsocket(struct sockaddr* remote_addr) { + int connfd = ::socket(remote_addr->sa_family, SOCK_STREAM, 0); + // SOCKADDR_PRINT(remote_addr); + if (connfd < 0) { + perror("socket"); + return -2; + } + + hio_t* io = hio_get(loop_->loop(), connfd); + assert(io != NULL); + hio_set_peeraddr(io, remote_addr, SOCKADDR_LEN(remote_addr)); + channel = std::make_shared(io); + return connfd; + } + + int bind(int local_port, const char* local_host = "0.0.0.0") { + sockaddr_u local_addr; + memset(&local_addr, 0, sizeof(local_addr)); + int ret = sockaddr_set_ipport(&local_addr, local_host, local_port); + if (ret != 0) { + return NABS(ret); + } + return bind(&local_addr.sa); + } + + int bind(struct sockaddr* local_addr) { + if (channel == NULL || channel->isClosed()) { + return -1; + } + int ret = ::bind(channel->fd(), local_addr, SOCKADDR_LEN(local_addr)); + if (ret != 0) { + perror("bind"); + } + return ret; + } + + // closesocket thread-safe + void closesocket() { + if (channel) { + loop_->runInLoop([this](){ + if (channel) { + setReconnect(NULL); + channel->close(); + } + }); + } + } + + int startConnect() { + if (channel == NULL || channel->isClosed()) { + int connfd = createsocket(&remote_addr.sa); + if (connfd < 0) { + hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, connfd); + return connfd; + } + } + if (channel == NULL || channel->status >= SocketChannel::CONNECTING) { + return -1; + } + if (connect_timeout) { + channel->setConnectTimeout(connect_timeout); + } + if (tls) { + channel->enableSSL(); + if (tls_setting) { + int ret = channel->newSslCtx(tls_setting); + if (ret != 0) { + hloge("new SSL_CTX failed: %d", ret); + closesocket(); + return ret; + } + } + if (!is_ipaddr(remote_host.c_str())) { + channel->setHostname(remote_host); + } + } + channel->onconnect = [this]() { + if (unpack_setting) { + channel->setUnpack(unpack_setting); + } + channel->startRead(); + if (onConnection) { + onConnection(channel); + } + if (reconn_setting) { + reconn_setting_reset(reconn_setting); + } + }; + channel->onread = [this](Buffer* buf) { + if (onMessage) { + onMessage(channel, buf); + } + }; + channel->onwrite = [this](Buffer* buf) { + if (onWriteComplete) { + onWriteComplete(channel, buf); + } + }; + channel->onclose = [this]() { + if (onConnection) { + onConnection(channel); + } + // reconnect + if (reconn_setting) { + startReconnect(); + } + }; + return channel->startConnect(); + } + + int startReconnect() { + if (!reconn_setting) return -1; + if (!reconn_setting_can_retry(reconn_setting)) return -2; + uint32_t delay = reconn_setting_calc_delay(reconn_setting); + hlogi("reconnect... cnt=%d, delay=%d", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay); + loop_->setTimeout(delay, [this](TimerID timerID){ + startConnect(); + }); + return 0; + } + + // start thread-safe + void start() { + loop_->runInLoop(std::bind(&TcpClientEventLoopTmpl::startConnect, this)); + } + + bool isConnected() { + if (channel == NULL) return false; + return channel->isConnected(); + } + + // send thread-safe + int send(const void* data, int size) { + if (!isConnected()) return -1; + return channel->write(data, size); + } + int send(Buffer* buf) { + return send(buf->data(), buf->size()); + } + int send(const std::string& str) { + return send(str.data(), str.size()); + } + + int withTLS(hssl_ctx_opt_t* opt = NULL) { + tls = true; + if (opt) { + if (tls_setting == NULL) { + HV_ALLOC_SIZEOF(tls_setting); + } + opt->endpoint = HSSL_CLIENT; + *tls_setting = *opt; + } + return 0; + } + + void setConnectTimeout(int ms) { + connect_timeout = ms; + } + + void setReconnect(reconn_setting_t* setting) { + if (setting == NULL) { + HV_FREE(reconn_setting); + return; + } + if (reconn_setting == NULL) { + HV_ALLOC_SIZEOF(reconn_setting); + } + *reconn_setting = *setting; + } + bool isReconnect() { + return reconn_setting && reconn_setting->cur_retry_cnt > 0; + } + + void setUnpack(unpack_setting_t* setting) { + if (setting == NULL) { + HV_FREE(unpack_setting); + return; + } + if (unpack_setting == NULL) { + HV_ALLOC_SIZEOF(unpack_setting); + } + *unpack_setting = *setting; + } + +public: + TSocketChannelPtr channel; + + std::string remote_host; + int remote_port; + sockaddr_u remote_addr; + int connect_timeout; + bool tls; + hssl_ctx_opt_t* tls_setting; + reconn_setting_t* reconn_setting; + unpack_setting_t* unpack_setting; + + // Callback + std::function onConnection; + std::function onMessage; + // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. + std::function onWriteComplete; + +private: + EventLoopPtr loop_; +}; + +template +class TcpClientTmpl : private EventLoopThread, public TcpClientEventLoopTmpl { +public: + TcpClientTmpl(EventLoopPtr loop = NULL) + : EventLoopThread(loop) + , TcpClientEventLoopTmpl(EventLoopThread::loop()) + , is_loop_owner(loop == NULL) + {} + virtual ~TcpClientTmpl() { + stop(true); + } + + const EventLoopPtr& loop() { + return EventLoopThread::loop(); + } + + // start thread-safe + void start(bool wait_threads_started = true) { + if (isRunning()) { + TcpClientEventLoopTmpl::start(); + } else { + EventLoopThread::start(wait_threads_started, [this]() { + TcpClientTmpl::startConnect(); + return 0; + }); + } + } + + // stop thread-safe + void stop(bool wait_threads_stopped = true) { + TcpClientEventLoopTmpl::closesocket(); + if (is_loop_owner) { + EventLoopThread::stop(wait_threads_stopped); + } + } + +private: + bool is_loop_owner; +}; + +typedef TcpClientTmpl TcpClient; + +} + +#endif // HV_TCP_CLIENT_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/TcpClientEventLoop_test.cpp b/external/libhv/libhv-1.3.2/evpp/TcpClientEventLoop_test.cpp new file mode 100644 index 0000000..8b0ac9e --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TcpClientEventLoop_test.cpp @@ -0,0 +1,108 @@ +/* + * TcpClientEventLoop_test.cpp + * + * @build make evpp + * @server bin/TcpServer_test 1234 + * @client bin/TcpClientEventLoop_test 1234 + * + */ + +#include "TcpClient.h" +#include "htime.h" + +#define TEST_RECONNECT 1 +#define TEST_TLS 0 + +using namespace hv; + +class MyTcpClient : public TcpClient { +public: + MyTcpClient(EventLoopPtr loop = NULL) : TcpClient(loop) { + onConnection = [this](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + // send(time) every 3s + setInterval(3000, [channel](TimerID timerID){ + if (channel->isConnected()) { + if (channel->isWriteComplete()) { + char str[DATETIME_FMT_BUFLEN] = {0}; + datetime_t dt = datetime_now(); + datetime_fmt(&dt, str); + channel->write(str); + } + } else { + killTimer(timerID); + } + }); + } else { + printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + if (isReconnect()) { + printf("reconnect cnt=%d, delay=%d\n", reconn_setting->cur_retry_cnt, reconn_setting->cur_delay); + } + }; + + onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + }; + } + + int connect(int port) { + int connfd = createsocket(port); + if (connfd < 0) { + return connfd; + } +#if TEST_RECONNECT + // reconnect: 1,2,4,8,10,10,10... + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + setReconnect(&reconn); +#endif + +#if TEST_TLS + withTLS(); +#endif + printf("client connect to port %d, connfd=%d ...\n", port, connfd); + start(); + return connfd; + } +}; +typedef std::shared_ptr MyTcpClientPtr; + +int TestMultiClientsRunInOneEventLoop(int port, int nclients) { + auto loop_thread = std::make_shared(); + loop_thread->start(); + + std::map clients; + for (int i = 0; i < nclients; ++i) { + MyTcpClient* client = new MyTcpClient(loop_thread->loop()); + client->connect(port); + clients[i] = MyTcpClientPtr(client); + } + + // press Enter to stop + while (getchar() != '\n'); + loop_thread->stop(); + loop_thread->join(); + + return 0; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + int nclients = 100; + if (argc > 2) { + nclients = atoi(argv[2]); + } + + return TestMultiClientsRunInOneEventLoop(port, nclients); +} diff --git a/external/libhv/libhv-1.3.2/evpp/TcpClient_test.cpp b/external/libhv/libhv-1.3.2/evpp/TcpClient_test.cpp new file mode 100644 index 0000000..2ac096e --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TcpClient_test.cpp @@ -0,0 +1,97 @@ +/* + * TcpClient_test.cpp + * + * @build make evpp + * @server bin/TcpServer_test 1234 + * @client bin/TcpClient_test 1234 + * + */ + +#include + +#include "TcpClient.h" +#include "htime.h" + +#define TEST_RECONNECT 1 +#define TEST_TLS 0 + +using namespace hv; + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: %s remote_port [remote_host]\n", argv[0]); + return -10; + } + int remote_port = atoi(argv[1]); + const char* remote_host = "127.0.0.1"; + if (argc > 2) { + remote_host = argv[2]; + } + + TcpClient cli; + int connfd = cli.createsocket(remote_port, remote_host); + if (connfd < 0) { + return -20; + } + printf("client connect to port %d, connfd=%d ...\n", remote_port, connfd); + cli.onConnection = [&cli](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + // send(time) every 3s + setInterval(3000, [channel](TimerID timerID){ + if (channel->isConnected()) { + if (channel->isWriteComplete()) { + char str[DATETIME_FMT_BUFLEN] = {0}; + datetime_t dt = datetime_now(); + datetime_fmt(&dt, str); + channel->write(str); + } + } else { + killTimer(timerID); + } + }); + } else { + printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + if (cli.isReconnect()) { + printf("reconnect cnt=%d, delay=%d\n", cli.reconn_setting->cur_retry_cnt, cli.reconn_setting->cur_delay); + } + }; + cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + }; + +#if TEST_RECONNECT + // reconnect: 1,2,4,8,10,10,10... + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + cli.setReconnect(&reconn); +#endif + +#if TEST_TLS + cli.withTLS(); +#endif + + cli.start(); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + cli.closesocket(); + } else if (str == "start") { + cli.start(); + } else if (str == "stop") { + cli.stop(); + break; + } else { + if (!cli.isConnected()) break; + cli.send(str); + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/TcpServer.h b/external/libhv/libhv-1.3.2/evpp/TcpServer.h new file mode 100644 index 0000000..61af120 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TcpServer.h @@ -0,0 +1,316 @@ +#ifndef HV_TCP_SERVER_HPP_ +#define HV_TCP_SERVER_HPP_ + +#include "hsocket.h" +#include "hssl.h" +#include "hlog.h" + +#include "EventLoopThreadPool.h" +#include "Channel.h" + +namespace hv { + +template +class TcpServerEventLoopTmpl { +public: + typedef std::shared_ptr TSocketChannelPtr; + + TcpServerEventLoopTmpl(EventLoopPtr loop = NULL) { + acceptor_loop = loop ? loop : std::make_shared(); + port = 0; + listenfd = -1; + tls = false; + tls_setting = NULL; + unpack_setting = NULL; + max_connections = 0xFFFFFFFF; + load_balance = LB_RoundRobin; + } + + virtual ~TcpServerEventLoopTmpl() { + HV_FREE(tls_setting); + HV_FREE(unpack_setting); + } + + EventLoopPtr loop(int idx = -1) { + return worker_threads.loop(idx); + } + + //@retval >=0 listenfd, <0 error + int createsocket(int port, const char* host = "0.0.0.0") { + listenfd = Listen(port, host); + if (listenfd < 0) return listenfd; + this->host = host; + this->port = port; + return listenfd; + } + // closesocket thread-safe + void closesocket() { + if (listenfd >= 0) { + hloop_t* loop = acceptor_loop->loop(); + if (loop) { + hio_t* listenio = hio_get(loop, listenfd); + assert(listenio != NULL); + hio_close_async(listenio); + } + listenfd = -1; + } + } + + void setMaxConnectionNum(uint32_t num) { + max_connections = num; + } + + void setLoadBalance(load_balance_e lb) { + load_balance = lb; + } + + // NOTE: totalThreadNum = 1 acceptor_thread + N worker_threads (N can be 0) + void setThreadNum(int num) { + worker_threads.setThreadNum(num); + } + + int startAccept() { + if (listenfd < 0) { + listenfd = createsocket(port, host.c_str()); + if (listenfd < 0) { + hloge("createsocket %s:%d return %d!\n", host.c_str(), port, listenfd); + return listenfd; + } + } + hloop_t* loop = acceptor_loop->loop(); + if (loop == NULL) return -2; + hio_t* listenio = haccept(loop, listenfd, onAccept); + assert(listenio != NULL); + hevent_set_userdata(listenio, this); + if (tls) { + hio_enable_ssl(listenio); + if (tls_setting) { + int ret = hio_new_ssl_ctx(listenio, tls_setting); + if (ret != 0) { + hloge("new SSL_CTX failed: %d", ret); + closesocket(); + return ret; + } + } + } + return 0; + } + + int stopAccept() { + if (listenfd < 0) return -1; + hloop_t* loop = acceptor_loop->loop(); + if (loop == NULL) return -2; + hio_t* listenio = hio_get(loop, listenfd); + assert(listenio != NULL); + return hio_del(listenio, HV_READ); + } + + // start thread-safe + void start(bool wait_threads_started = true) { + if (worker_threads.threadNum() > 0) { + worker_threads.start(wait_threads_started); + } + acceptor_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::startAccept, this)); + } + // stop thread-safe + void stop(bool wait_threads_stopped = true) { + closesocket(); + if (worker_threads.threadNum() > 0) { + worker_threads.stop(wait_threads_stopped); + } + } + + int withTLS(hssl_ctx_opt_t* opt = NULL) { + tls = true; + if (opt) { + if (tls_setting == NULL) { + HV_ALLOC_SIZEOF(tls_setting); + } + opt->endpoint = HSSL_SERVER; + *tls_setting = *opt; + } + return 0; + } + + void setUnpack(unpack_setting_t* setting) { + if (setting == NULL) { + HV_FREE(unpack_setting); + return; + } + if (unpack_setting == NULL) { + HV_ALLOC_SIZEOF(unpack_setting); + } + *unpack_setting = *setting; + } + + // channel + const TSocketChannelPtr& addChannel(hio_t* io) { + uint32_t id = hio_id(io); + auto channel = std::make_shared(io); + std::lock_guard locker(mutex_); + channels[id] = channel; + return channels[id]; + } + + TSocketChannelPtr getChannelById(uint32_t id) { + std::lock_guard locker(mutex_); + auto iter = channels.find(id); + return iter != channels.end() ? iter->second : NULL; + } + + void removeChannel(const TSocketChannelPtr& channel) { + uint32_t id = channel->id(); + std::lock_guard locker(mutex_); + channels.erase(id); + } + + size_t connectionNum() { + std::lock_guard locker(mutex_); + return channels.size(); + } + + int foreachChannel(std::function fn) { + std::lock_guard locker(mutex_); + for (auto& pair : channels) { + fn(pair.second); + } + return channels.size(); + } + + // broadcast thread-safe + int broadcast(const void* data, int size) { + return foreachChannel([data, size](const TSocketChannelPtr& channel) { + channel->write(data, size); + }); + } + + int broadcast(const std::string& str) { + return broadcast(str.data(), str.size()); + } + +private: + static void newConnEvent(hio_t* connio) { + TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio); + if (server->connectionNum() >= server->max_connections) { + hlogw("over max_connections"); + hio_close(connio); + return; + } + + // NOTE: attach to worker loop + EventLoop* worker_loop = currentThreadEventLoop; + assert(worker_loop != NULL); + hio_attach(worker_loop->loop(), connio); + + const TSocketChannelPtr& channel = server->addChannel(connio); + channel->status = SocketChannel::CONNECTED; + + channel->onread = [server, &channel](Buffer* buf) { + if (server->onMessage) { + server->onMessage(channel, buf); + } + }; + channel->onwrite = [server, &channel](Buffer* buf) { + if (server->onWriteComplete) { + server->onWriteComplete(channel, buf); + } + }; + channel->onclose = [server, &channel]() { + EventLoop* worker_loop = currentThreadEventLoop; + assert(worker_loop != NULL); + --worker_loop->connectionNum; + + channel->status = SocketChannel::CLOSED; + if (server->onConnection) { + server->onConnection(channel); + } + server->removeChannel(channel); + // NOTE: After removeChannel, channel may be destroyed, + // so in this lambda function, no code should be added below. + }; + + if (server->unpack_setting) { + channel->setUnpack(server->unpack_setting); + } + channel->startRead(); + if (server->onConnection) { + server->onConnection(channel); + } + } + + static void onAccept(hio_t* connio) { + TcpServerEventLoopTmpl* server = (TcpServerEventLoopTmpl*)hevent_userdata(connio); + // NOTE: detach from acceptor loop + hio_detach(connio); + EventLoopPtr worker_loop = server->worker_threads.nextLoop(server->load_balance); + if (worker_loop == NULL) { + worker_loop = server->acceptor_loop; + } + ++worker_loop->connectionNum; + worker_loop->runInLoop(std::bind(&TcpServerEventLoopTmpl::newConnEvent, connio)); + } + +public: + std::string host; + int port; + int listenfd; + bool tls; + hssl_ctx_opt_t* tls_setting; + unpack_setting_t* unpack_setting; + // Callback + std::function onConnection; + std::function onMessage; + // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. + std::function onWriteComplete; + + uint32_t max_connections; + load_balance_e load_balance; + +private: + // id => TSocketChannelPtr + std::map channels; // GUAREDE_BY(mutex_) + std::mutex mutex_; + + EventLoopPtr acceptor_loop; + EventLoopThreadPool worker_threads; +}; + +template +class TcpServerTmpl : private EventLoopThread, public TcpServerEventLoopTmpl { +public: + TcpServerTmpl(EventLoopPtr loop = NULL) + : EventLoopThread(loop) + , TcpServerEventLoopTmpl(EventLoopThread::loop()) + , is_loop_owner(loop == NULL) + {} + virtual ~TcpServerTmpl() { + stop(true); + } + + const EventLoopPtr& loop(int idx = -1) { + return TcpServerEventLoopTmpl::loop(idx); + } + + // start thread-safe + void start(bool wait_threads_started = true) { + TcpServerEventLoopTmpl::start(wait_threads_started); + EventLoopThread::start(wait_threads_started); + } + + // stop thread-safe + void stop(bool wait_threads_stopped = true) { + if (is_loop_owner) { + EventLoopThread::stop(wait_threads_stopped); + } + TcpServerEventLoopTmpl::stop(wait_threads_stopped); + } + +private: + bool is_loop_owner; +}; + +typedef TcpServerTmpl TcpServer; + +} + +#endif // HV_TCP_SERVER_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/TcpServer_test.cpp b/external/libhv/libhv-1.3.2/evpp/TcpServer_test.cpp new file mode 100644 index 0000000..9af3704 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TcpServer_test.cpp @@ -0,0 +1,75 @@ +/* + * TcpServer_test.cpp + * + * @build make evpp + * @server bin/TcpServer_test 1234 + * @client bin/TcpClient_test 1234 + * + */ + +#include + +#include "TcpServer.h" + +using namespace hv; + +#define TEST_TLS 0 + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + hlog_set_level(LOG_LEVEL_DEBUG); + + TcpServer srv; + int listenfd = srv.createsocket(port); + if (listenfd < 0) { + return -20; + } + printf("server listen on port %d, listenfd=%d ...\n", port, listenfd); + srv.onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("%s connected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid()); + } else { + printf("%s disconnected! connfd=%d id=%d tid=%ld\n", peeraddr.c_str(), channel->fd(), channel->id(), currentThreadEventLoop->tid()); + } + }; + srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + // echo + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + channel->write(buf); + }; + srv.setThreadNum(4); + srv.setLoadBalance(LB_LeastConnections); + +#if TEST_TLS + hssl_ctx_opt_t ssl_opt; + memset(&ssl_opt, 0, sizeof(hssl_ctx_opt_t)); + ssl_opt.crt_file = "cert/server.crt"; + ssl_opt.key_file = "cert/server.key"; + ssl_opt.verify_peer = 0; + srv.withTLS(&ssl_opt); +#endif + + srv.start(); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + srv.closesocket(); + } else if (str == "start") { + srv.start(); + } else if (str == "stop") { + srv.stop(); + break; + } else { + srv.broadcast(str.data(), str.size()); + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/TimerThread.h b/external/libhv/libhv-1.3.2/evpp/TimerThread.h new file mode 100644 index 0000000..8388fe0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TimerThread.h @@ -0,0 +1,47 @@ +#ifndef HV_TIMER_THREAD_HPP_ +#define HV_TIMER_THREAD_HPP_ + +#include "EventLoopThread.h" + +namespace hv { + +class TimerThread : public EventLoopThread { +public: + std::atomic nextTimerID; + TimerThread() : EventLoopThread() { + nextTimerID = 0; + start(); + } + + virtual ~TimerThread() { + stop(); + join(); + } + +public: + // setTimer, setTimeout, killTimer, resetTimer thread-safe + TimerID setTimer(int timeout_ms, TimerCallback cb, uint32_t repeat = INFINITE) { + TimerID timerID = ++nextTimerID; + loop()->setTimerInLoop(timeout_ms, cb, repeat, timerID); + return timerID; + } + // alias javascript setTimeout, setInterval + TimerID setTimeout(int timeout_ms, TimerCallback cb) { + return setTimer(timeout_ms, cb, 1); + } + TimerID setInterval(int interval_ms, TimerCallback cb) { + return setTimer(interval_ms, cb, INFINITE); + } + + void killTimer(TimerID timerID) { + loop()->killTimer(timerID); + } + + void resetTimer(TimerID timerID, int timeout_ms = 0) { + loop()->resetTimer(timerID, timeout_ms); + } +}; + +} // end namespace hv + +#endif // HV_TIMER_THREAD_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/TimerThread_test.cpp b/external/libhv/libhv-1.3.2/evpp/TimerThread_test.cpp new file mode 100644 index 0000000..f572f30 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/TimerThread_test.cpp @@ -0,0 +1,55 @@ +/* + * TimerThread_test.cpp + * + * @build: make evpp + * + */ + +#include "TimerThread.h" +#include "singleton.h" + +namespace hv { + +class GlobalTimerThread : public TimerThread { + SINGLETON_DECL(GlobalTimerThread) +protected: + GlobalTimerThread() : TimerThread() {} + ~GlobalTimerThread() {} + +public: + static TimerID setTimeout(int timeout_ms, TimerCallback cb) { + return GlobalTimerThread::instance()->setTimer(timeout_ms, cb, 1); + } + + static void clearTimeout(TimerID timerID) { + GlobalTimerThread::instance()->killTimer(timerID); + } + + static TimerID setInterval(int interval_ms, TimerCallback cb) { + return GlobalTimerThread::instance()->setTimer(interval_ms, cb, INFINITE); + } + + static void clearInterval(TimerID timerID) { + GlobalTimerThread::instance()->killTimer(timerID); + } +}; + +SINGLETON_IMPL(GlobalTimerThread) + +} // end namespace hv + +int main(int argc, char* argv[]) { + hv::GlobalTimerThread::setTimeout(3000, [](hv::TimerID timerID) { + printf("setTimeout timerID=%lu time=%lus\n", (unsigned long)timerID, (unsigned long)time(NULL)); + }); + + hv::GlobalTimerThread::setInterval(1000, [](hv::TimerID timerID) { + printf("setInterval timerID=%lu time=%lus\n", (unsigned long)timerID, (unsigned long)time(NULL)); + }); + + // press Enter to stop + while (getchar() != '\n'); + + hv::GlobalTimerThread::exitInstance(); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/UdpClient.h b/external/libhv/libhv-1.3.2/evpp/UdpClient.h new file mode 100644 index 0000000..2aba963 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/UdpClient.h @@ -0,0 +1,199 @@ +#ifndef HV_UDP_CLIENT_HPP_ +#define HV_UDP_CLIENT_HPP_ + +#include "hsocket.h" + +#include "EventLoopThread.h" +#include "Channel.h" + +namespace hv { + +template +class UdpClientEventLoopTmpl { +public: + typedef std::shared_ptr TSocketChannelPtr; + + UdpClientEventLoopTmpl(EventLoopPtr loop = NULL) { + loop_ = loop ? loop : std::make_shared(); + remote_port = 0; +#if WITH_KCP + kcp_setting = NULL; +#endif + } + + virtual ~UdpClientEventLoopTmpl() { +#if WITH_KCP + HV_FREE(kcp_setting); +#endif + } + + const EventLoopPtr& loop() { + return loop_; + } + + // NOTE: By default, not bind local port. If necessary, you can call bind() after createsocket(). + // @retval >=0 sockfd, <0 error + int createsocket(int remote_port, const char* remote_host = "127.0.0.1") { + hio_t* io = hloop_create_udp_client(loop_->loop(), remote_host, remote_port); + if (io == NULL) return -1; + this->remote_host = remote_host; + this->remote_port = remote_port; + channel = std::make_shared(io); + int sockfd = channel->fd(); + if (hv_strendswith(remote_host, ".255")) { + udp_broadcast(sockfd, 1); + } + return sockfd; + } + + int bind(int local_port, const char* local_host = "0.0.0.0") { + if (channel == NULL || channel->isClosed()) { + return -1; + } + sockaddr_u local_addr; + memset(&local_addr, 0, sizeof(local_addr)); + int ret = sockaddr_set_ipport(&local_addr, local_host, local_port); + if (ret != 0) { + return NABS(ret); + } + ret = ::bind(channel->fd(), &local_addr.sa, SOCKADDR_LEN(&local_addr)); + if (ret != 0) { + perror("bind"); + } + return ret; + } + + // closesocket thread-safe + void closesocket() { + if (channel) { + channel->close(true); + } + } + + int startRecv() { + if (channel == NULL || channel->isClosed()) { + int sockfd = createsocket(remote_port, remote_host.c_str()); + if (sockfd < 0) { + hloge("createsocket %s:%d return %d!\n", remote_host.c_str(), remote_port, sockfd); + return sockfd; + } + } + if (channel == NULL || channel->isClosed()) { + return -1; + } + channel->onread = [this](Buffer* buf) { + if (onMessage) { + onMessage(channel, buf); + } + }; + channel->onwrite = [this](Buffer* buf) { + if (onWriteComplete) { + onWriteComplete(channel, buf); + } + }; +#if WITH_KCP + if (kcp_setting) { + hio_set_kcp(channel->io(), kcp_setting); + } +#endif + return channel->startRead(); + } + + int stopRecv() { + if (channel == NULL) return -1; + return channel->stopRead(); + } + + // start thread-safe + void start() { + loop_->runInLoop(std::bind(&UdpClientEventLoopTmpl::startRecv, this)); + } + + // sendto thread-safe + int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) { + if (channel == NULL) return -1; + std::lock_guard locker(sendto_mutex); + if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr)); + return channel->write(data, size); + } + int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) { + return sendto(buf->data(), buf->size(), peeraddr); + } + int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) { + return sendto(str.data(), str.size(), peeraddr); + } + +#if WITH_KCP + void setKcp(kcp_setting_t* setting) { + if (setting == NULL) { + HV_FREE(kcp_setting); + return; + } + if (kcp_setting == NULL) { + HV_ALLOC_SIZEOF(kcp_setting); + } + *kcp_setting = *setting; + } +#endif + +public: + TSocketChannelPtr channel; + + std::string remote_host; + int remote_port; + +#if WITH_KCP + kcp_setting_t* kcp_setting; +#endif + // Callback + std::function onMessage; + // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. + std::function onWriteComplete; + +private: + std::mutex sendto_mutex; + EventLoopPtr loop_; +}; + +template +class UdpClientTmpl : private EventLoopThread, public UdpClientEventLoopTmpl { +public: + UdpClientTmpl(EventLoopPtr loop = NULL) + : EventLoopThread(loop) + , UdpClientEventLoopTmpl(EventLoopThread::loop()) + , is_loop_owner(loop == NULL) + {} + virtual ~UdpClientTmpl() { + stop(true); + } + + const EventLoopPtr& loop() { + return EventLoopThread::loop(); + } + + // start thread-safe + void start(bool wait_threads_started = true) { + if (isRunning()) { + UdpClientEventLoopTmpl::start(); + } else { + EventLoopThread::start(wait_threads_started, std::bind(&UdpClientTmpl::startRecv, this)); + } + } + + // stop thread-safe + void stop(bool wait_threads_stopped = true) { + UdpClientEventLoopTmpl::closesocket(); + if (is_loop_owner) { + EventLoopThread::stop(wait_threads_stopped); + } + } + +private: + bool is_loop_owner; +}; + +typedef UdpClientTmpl UdpClient; + +} + +#endif // HV_UDP_CLIENT_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/UdpClient_test.cpp b/external/libhv/libhv-1.3.2/evpp/UdpClient_test.cpp new file mode 100644 index 0000000..4ab91d7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/UdpClient_test.cpp @@ -0,0 +1,62 @@ +/* + * UdpClient_test.cpp + * + * @build make evpp + * @server bin/UdpServer_test 1234 + * @client bin/UdpClient_test 1234 + * + */ + +#include + +#include "UdpClient.h" +#include "htime.h" + +using namespace hv; + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: %s remote_port [remote_host]\n", argv[0]); + return -10; + } + int remote_port = atoi(argv[1]); + const char* remote_host = "127.0.0.1"; + if (argc > 2) { + remote_host = argv[2]; + } + + UdpClient cli; + int sockfd = cli.createsocket(remote_port, remote_host); + if (sockfd < 0) { + return -20; + } + printf("client sendto port %d, sockfd=%d ...\n", remote_port, sockfd); + cli.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + }; + cli.start(); + + // sendto(time) every 3s + cli.loop()->setInterval(3000, [&cli](TimerID timerID) { + char str[DATETIME_FMT_BUFLEN] = {0}; + datetime_t dt = datetime_now(); + datetime_fmt(&dt, str); + cli.sendto(str); + }); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + cli.closesocket(); + } else if (str == "start") { + cli.start(); + } else if (str == "stop") { + cli.stop(); + break; + } else { + cli.sendto(str); + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/UdpServer.h b/external/libhv/libhv-1.3.2/evpp/UdpServer.h new file mode 100644 index 0000000..2db27b3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/UdpServer.h @@ -0,0 +1,174 @@ +#ifndef HV_UDP_SERVER_HPP_ +#define HV_UDP_SERVER_HPP_ + +#include "hsocket.h" + +#include "EventLoopThreadPool.h" +#include "Channel.h" + +namespace hv { + +template +class UdpServerEventLoopTmpl { +public: + typedef std::shared_ptr TSocketChannelPtr; + + UdpServerEventLoopTmpl(EventLoopPtr loop = NULL) { + loop_ = loop ? loop : std::make_shared(); + port = 0; +#if WITH_KCP + kcp_setting = NULL; +#endif + } + + virtual ~UdpServerEventLoopTmpl() { +#if WITH_KCP + HV_FREE(kcp_setting); +#endif + } + + const EventLoopPtr& loop() { + return loop_; + } + + //@retval >=0 bindfd, <0 error + int createsocket(int port, const char* host = "0.0.0.0") { + hio_t* io = hloop_create_udp_server(loop_->loop(), host, port); + if (io == NULL) return -1; + this->host = host; + this->port = port; + channel = std::make_shared(io); + return channel->fd(); + } + // closesocket thread-safe + void closesocket() { + if (channel) { + channel->close(true); + } + } + + int startRecv() { + if (channel == NULL || channel->isClosed()) { + int bindfd = createsocket(port, host.c_str()); + if (bindfd < 0) { + hloge("createsocket %s:%d return %d!\n", host.c_str(), port, bindfd); + return bindfd; + } + } + if (channel == NULL || channel->isClosed()) { + return -1; + } + channel->onread = [this](Buffer* buf) { + if (onMessage) { + onMessage(channel, buf); + } + }; + channel->onwrite = [this](Buffer* buf) { + if (onWriteComplete) { + onWriteComplete(channel, buf); + } + }; +#if WITH_KCP + if (kcp_setting) { + hio_set_kcp(channel->io(), kcp_setting); + } +#endif + return channel->startRead(); + } + + int stopRecv() { + if (channel == NULL) return -1; + return channel->stopRead(); + } + + // start thread-safe + void start() { + loop_->runInLoop(std::bind(&UdpServerEventLoopTmpl::startRecv, this)); + } + + // sendto thread-safe + int sendto(const void* data, int size, struct sockaddr* peeraddr = NULL) { + if (channel == NULL) return -1; + std::lock_guard locker(sendto_mutex); + if (peeraddr) hio_set_peeraddr(channel->io(), peeraddr, SOCKADDR_LEN(peeraddr)); + return channel->write(data, size); + } + int sendto(Buffer* buf, struct sockaddr* peeraddr = NULL) { + return sendto(buf->data(), buf->size(), peeraddr); + } + int sendto(const std::string& str, struct sockaddr* peeraddr = NULL) { + return sendto(str.data(), str.size(), peeraddr); + } + +#if WITH_KCP + void setKcp(kcp_setting_t* setting) { + if (setting == NULL) { + HV_FREE(kcp_setting); + return; + } + if (kcp_setting == NULL) { + HV_ALLOC_SIZEOF(kcp_setting); + } + *kcp_setting = *setting; + } +#endif + +public: + std::string host; + int port; + TSocketChannelPtr channel; +#if WITH_KCP + kcp_setting_t* kcp_setting; +#endif + // Callback + std::function onMessage; + // NOTE: Use Channel::isWriteComplete in onWriteComplete callback to determine whether all data has been written. + std::function onWriteComplete; + +private: + std::mutex sendto_mutex; + EventLoopPtr loop_; +}; + +template +class UdpServerTmpl : private EventLoopThread, public UdpServerEventLoopTmpl { +public: + UdpServerTmpl(EventLoopPtr loop = NULL) + : EventLoopThread(loop) + , UdpServerEventLoopTmpl(EventLoopThread::loop()) + , is_loop_owner(loop == NULL) + {} + virtual ~UdpServerTmpl() { + stop(true); + } + + const EventLoopPtr& loop() { + return EventLoopThread::loop(); + } + + // start thread-safe + void start(bool wait_threads_started = true) { + if (isRunning()) { + UdpServerEventLoopTmpl::start(); + } else { + EventLoopThread::start(wait_threads_started, std::bind(&UdpServerTmpl::startRecv, this)); + } + } + + // stop thread-safe + void stop(bool wait_threads_stopped = true) { + UdpServerEventLoopTmpl::closesocket(); + if (is_loop_owner) { + EventLoopThread::stop(wait_threads_stopped); + } + } + +private: + bool is_loop_owner; +}; + +typedef UdpServerTmpl UdpServer; + +} + +#endif // HV_UDP_SERVER_HPP_ diff --git a/external/libhv/libhv-1.3.2/evpp/UdpServer_test.cpp b/external/libhv/libhv-1.3.2/evpp/UdpServer_test.cpp new file mode 100644 index 0000000..7e4fe46 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/UdpServer_test.cpp @@ -0,0 +1,51 @@ +/* + * UdpServer_test.cpp + * + * @build make evpp + * @server bin/UdpServer_test 1234 + * @client bin/UdpClient_test 1234 + * + */ + +#include + +#include "UdpServer.h" + +using namespace hv; + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + UdpServer srv; + int bindfd = srv.createsocket(port); + if (bindfd < 0) { + return -20; + } + printf("server bind on port %d, bindfd=%d ...\n", port, bindfd); + srv.onMessage = [](const SocketChannelPtr& channel, Buffer* buf) { + // echo + printf("< %.*s\n", (int)buf->size(), (char*)buf->data()); + channel->write(buf); + }; + srv.start(); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + srv.closesocket(); + } else if (str == "start") { + srv.start(); + } else if (str == "stop") { + srv.stop(); + break; + } else { + srv.sendto(str); + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/evpp/build_test.sh b/external/libhv/libhv-1.3.2/evpp/build_test.sh new file mode 100755 index 0000000..51eee38 --- /dev/null +++ b/external/libhv/libhv-1.3.2/evpp/build_test.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. + +cd ${ROOT_DIR} +make evpp diff --git a/external/libhv/libhv-1.3.2/examples/CMakeLists.txt b/external/libhv/libhv-1.3.2/examples/CMakeLists.txt new file mode 100644 index 0000000..327c3b2 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/CMakeLists.txt @@ -0,0 +1,161 @@ +list(APPEND EXAMPLES + hloop_test + htimer_test + nc + tinyhttpd + tinyproxyd + tcp_client_test + tcp_echo_server + tcp_chat_server + tcp_proxy_server + udp_echo_server + udp_proxy_server + socks5_proxy_server + jsonrpc_client + jsonrpc_server +) + +include_directories(.. ../base ../ssl ../event ../util) + +add_executable(hloop_test hloop_test.c) +target_link_libraries(hloop_test ${HV_LIBRARIES}) + +add_executable(htimer_test htimer_test.c) +target_link_libraries(htimer_test ${HV_LIBRARIES}) + +add_executable(nc nc.c) +target_link_libraries(nc ${HV_LIBRARIES}) + +add_executable(tinyhttpd tinyhttpd.c) +target_link_libraries(tinyhttpd ${HV_LIBRARIES}) + +add_executable(tinyproxyd tinyproxyd.c) +target_link_libraries(tinyproxyd ${HV_LIBRARIES}) + +add_executable(tcp_client_test tcp_client_test.c) +target_link_libraries(tcp_client_test ${HV_LIBRARIES}) + +add_executable(tcp_echo_server tcp_echo_server.c) +target_link_libraries(tcp_echo_server ${HV_LIBRARIES}) + +add_executable(tcp_chat_server tcp_chat_server.c) +target_link_libraries(tcp_chat_server ${HV_LIBRARIES}) + +add_executable(tcp_proxy_server tcp_proxy_server.c) +target_link_libraries(tcp_proxy_server ${HV_LIBRARIES}) + +add_executable(udp_echo_server udp_echo_server.c) +target_link_libraries(udp_echo_server ${HV_LIBRARIES}) + +add_executable(udp_proxy_server udp_proxy_server.c) +target_link_libraries(udp_proxy_server ${HV_LIBRARIES}) + +add_executable(socks5_proxy_server socks5_proxy_server.c) +target_link_libraries(socks5_proxy_server ${HV_LIBRARIES}) + +add_executable(jsonrpc_client jsonrpc/jsonrpc_client.c jsonrpc/cJSON.c) +target_compile_definitions(jsonrpc_client PRIVATE CJSON_HIDE_SYMBOLS) +target_link_libraries(jsonrpc_client ${HV_LIBRARIES}) + +add_executable(jsonrpc_server jsonrpc/jsonrpc_server.c jsonrpc/cJSON.c) +target_compile_definitions(jsonrpc_server PRIVATE CJSON_HIDE_SYMBOLS) +target_link_libraries(jsonrpc_server ${HV_LIBRARIES}) + +if(WITH_EVPP) + include_directories(../cpputil ../evpp) + + # hmain_test + add_executable(hmain_test hmain_test.cpp) + target_link_libraries(hmain_test ${HV_LIBRARIES}) + + # nmap + glob_headers_and_sources(NMAP_FILES nmap) + add_executable(nmap ${NMAP_FILES}) + target_compile_definitions(nmap PRIVATE PRINT_DEBUG) + target_link_libraries(nmap ${HV_LIBRARIES}) + + list(APPEND EXAMPLES hmain_test nmap) +if(WITH_HTTP) + include_directories(../http) + + # wrk + add_executable(wrk wrk.cpp) + target_link_libraries(wrk ${HV_LIBRARIES}) + + list(APPEND EXAMPLES wrk) +if(WITH_HTTP_SERVER) + include_directories(../http/server) + + # http_server_test + add_executable(http_server_test http_server_test.cpp) + target_link_libraries(http_server_test ${HV_LIBRARIES}) + + # websocket_server_test + add_executable(websocket_server_test websocket_server_test.cpp) + target_link_libraries(websocket_server_test ${HV_LIBRARIES}) + + list(APPEND EXAMPLES http_server_test websocket_server_test) +endif() + +if(WITH_HTTP_CLIENT) + include_directories(../http/client) + + # curl + set(CURL_TARGET_NAME curl) + if(WITH_CURL) + set(CURL_TARGET_NAME hv_curl) + endif() + add_executable(${CURL_TARGET_NAME} curl.cpp) + if(WITH_CURL) + set_target_properties(${CURL_TARGET_NAME} PROPERTIES OUTPUT_NAME curl) + endif() + target_link_libraries(${CURL_TARGET_NAME} ${HV_LIBRARIES}) + + # wget + add_executable(wget wget.cpp) + target_link_libraries(wget ${HV_LIBRARIES}) + + # consul + glob_headers_and_sources(CONSUL_FILES consul) + add_executable(consul ${CONSUL_FILES}) + target_compile_definitions(consul PRIVATE PRINT_DEBUG) + target_link_libraries(consul ${HV_LIBRARIES}) + + # http_client_test + add_executable(http_client_test http_client_test.cpp) + target_link_libraries(http_client_test ${HV_LIBRARIES}) + + # websocket_client_test + add_executable(websocket_client_test websocket_client_test.cpp) + target_link_libraries(websocket_client_test ${HV_LIBRARIES}) + + list(APPEND EXAMPLES ${CURL_TARGET_NAME} wget consul http_client_test websocket_client_test) + + if(WITH_HTTP_SERVER) + # httpd + glob_headers_and_sources(HTTPD_FILES httpd) + add_executable(httpd ${HTTPD_FILES}) + target_link_libraries(httpd ${HV_LIBRARIES}) + list(APPEND EXAMPLES httpd) + endif() +endif() + +endif() +endif() + +if(WITH_MQTT) + include_directories(../mqtt) + + add_executable(mqtt_sub mqtt/mqtt_sub.c) + target_link_libraries(mqtt_sub ${HV_LIBRARIES}) + + add_executable(mqtt_pub mqtt/mqtt_pub.c) + target_link_libraries(mqtt_pub ${HV_LIBRARIES}) + + add_executable(mqtt_client_test mqtt/mqtt_client_test.cpp) + target_link_libraries(mqtt_client_test ${HV_LIBRARIES}) + + list(APPEND EXAMPLES mqtt_sub mqtt_pub mqtt_client_test) +endif() + +add_custom_target(examples DEPENDS ${EXAMPLES}) diff --git a/external/libhv/libhv-1.3.2/examples/README.md b/external/libhv/libhv-1.3.2/examples/README.md new file mode 100644 index 0000000..273f2e3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/README.md @@ -0,0 +1,32 @@ +## 目录结构 + +``` +. +├── consul/ consul服务注册与发现 +├── httpd/ HTTP服务端 +├── jsonrpc/ json RPC示例 +├── mqtt/ MQTT发布订阅示例 +├── multi-thread/ 多线程网络编程示例 +├── nmap/ 网络扫描工具 +├── protorpc/ protobuf RPC示例 +├── curl.cpp HTTP请求工具 +├── hloop_test.c 事件循环测试代码 +├── hmain_test.cpp 命令行程序示例代码 +├── htimer_test.c 定时器测试代码 +├── http_client_test.c HTTP客户端测试代码 +├── http_server_test.c HTTP服务端测试代码 +├── nc.c 网络连接工具 +├── socks5_proxy_server.c SOCKS5代理服务 +├── tcp_chat_server.c TCP聊天服务 +├── tcp_echo_server.c TCP回显服务 +├── tcp_proxy_server.c TCP代理服务 +├── tinyhttpd.c 微型HTTP服务 +├── tinyproxyd.c 微型HTTP代理服务 +├── udp_echo_server.c UDP回显服务 +├── udp_proxy_server.c UDP代理服务 +├── websocket_client_test.c WebSocket客户端测试代码 +├── websocket_server_test.c WebSocket服务端测试代码 +├── wget.cpp HTTP文件下载工具 +└── wrk.cpp HTTP压测工具 + +``` diff --git a/external/libhv/libhv-1.3.2/examples/consul/consul.cpp b/external/libhv/libhv-1.3.2/examples/consul/consul.cpp new file mode 100644 index 0000000..4f410a8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/consul/consul.cpp @@ -0,0 +1,144 @@ +#include "consul.h" + +#include "HttpClient.h" +using namespace hv; + +#include "json.hpp" +using json = nlohmann::json; + +#define PROTOCOL "http://" +#define API_VERSION "v1" + +static const char url_register[] = "/agent/service/register"; +static const char url_deregister[] = "/agent/service/deregister"; +static const char url_discover[] = "/catalog/service"; + +static std::string make_url(const char* ip, int port, const char* url) { + return asprintf(PROTOCOL "%s:%d/" API_VERSION "%s", ip, port, url); +} + +static std::string make_ServiceID(consul_service_t* service) { + return asprintf("%s-%s:%d", service->name, service->ip, service->port); +} + +/* +{ + "ID": "redis1", + "Name": "redis", + "Tags": [ + "primary", + "v1" + ], + "Address": "127.0.0.1", + "Port": 8000, + "Meta": { + "redis_version": "4.0" + }, + "EnableTagOverride": false, + "Check": { + "DeregisterCriticalServiceAfter": "90m", + "Args": ["/usr/local/bin/check_redis.py"], + "HTTP": "http://localhost:5000/health", + "Interval": "10s", + "TTL": "15s" + }, + "Weights": { + "Passing": 10, + "Warning": 1 + } +} + */ +int register_service(consul_node_t* node, consul_service_t* service, consul_health_t* health) { + HttpRequest req; + req.method = HTTP_PUT; + req.url = make_url(node->ip, node->port, url_register); + req.content_type = APPLICATION_JSON; + + json jservice; + jservice["Name"] = service->name; + if (*service->ip) { + jservice["Address"] = service->ip; + } + jservice["Port"] = service->port; + jservice["ID"] = make_ServiceID(service); + + json jcheck; + if (*health->url == '\0') { + snprintf(health->url, sizeof(health->url), "%s:%d", service->ip, service->port); + } + jcheck[health->protocol] = health->url; + jcheck["Interval"] = asprintf("%dms", health->interval); + jcheck["DeregisterCriticalServiceAfter"] = asprintf("%dms", health->interval * 3); + jservice["Check"] = jcheck; + + req.body = jservice.dump(); + printd("PUT %s\n", req.url.c_str()); + printd("%s\n", req.body.c_str()); + + HttpResponse res; + int ret = http_client_send(&req, &res); + printd("%s\n", res.body.c_str()); + return ret; +} + +int deregister_service(consul_node_t* node, consul_service_t* service) { + std::string url = make_url(node->ip, node->port, url_deregister); + url += '/'; + url += make_ServiceID(service); + + HttpRequest req; + req.method = HTTP_PUT; + req.url = url; + req.content_type = APPLICATION_JSON; + printd("PUT %s\n", req.url.c_str()); + + HttpResponse res; + int ret = http_client_send(&req, &res); + printd("%s\n", res.body.c_str()); + return ret; +} + +int discover_services(consul_node_t* node, const char* service_name, std::vector& services) { + std::string url = make_url(node->ip, node->port, url_discover); + url += '/'; + url += service_name; + + HttpRequest req; + req.method = HTTP_GET; + req.url = url; + + HttpResponse res; + printd("GET %s\n", req.url.c_str()); + int ret = http_client_send(&req, &res); + if (ret != 0) return ret; + printd("%s\n", res.body.c_str()); + + json jroot = json::parse(res.body); + if (!jroot.is_array()) return -1; + if (jroot.size() == 0) return 0; + + consul_service_t service; + std::string name, ip; + services.clear(); + for (size_t i = 0; i < jroot.size(); ++i) { + auto jservice = jroot[i]; + name = jservice["ServiceName"]; + if (jservice.contains("Address")) { + ip = jservice["Address"]; + } else if (jservice.contains("ServiceAddress")) { + ip = jservice["ServiceAddress"]; + } else if (jservice.contains("ServiceAddress6")) { + ip = jservice["ServiceAddress6"]; + } else { + continue; + } + int port = jservice["ServicePort"]; + + strncpy(service.name, name.c_str(), sizeof(service.name)); + strncpy(service.ip, ip.c_str(), sizeof(service.ip)); + service.port = port; + services.emplace_back(service); + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/consul/consul.h b/external/libhv/libhv-1.3.2/examples/consul/consul.h new file mode 100644 index 0000000..d02a0ae --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/consul/consul.h @@ -0,0 +1,53 @@ +#ifndef CONSUL_H_ +#define CONSUL_H_ + +#include +#include + +typedef struct consul_node_s { + // node + char ip[64]; + int port; + + consul_node_s() { + strcpy(ip, "127.0.0.1"); + port = 8500; + } +} consul_node_t; + +typedef struct consul_service_s { + // service + char name[64]; + char ip[64]; + int port; + + consul_service_s() { + name[0] = '\0'; + strcpy(ip, "127.0.0.1"); + port = 0; + } +} consul_service_t; + +typedef struct consul_health_s { + // check + char protocol[32]; // TCP,HTTP + char url[256]; + char status[32]; // any,passing,warning,critical + + int interval; // ms + int timeout; // ms + + consul_health_s() { + strcpy(protocol, "TCP"); + url[0] = '\0'; + strcpy(status, "passing"); + interval = 10000; + timeout = 3000; + } +} consul_health_t; + +int register_service(consul_node_t* node, consul_service_t* service, consul_health_t* health); +int deregister_service(consul_node_t* node, consul_service_t* service); +int discover_services(consul_node_t* node, const char* service_name, std::vector& services); + +#endif // CONSUL_H_ diff --git a/external/libhv/libhv-1.3.2/examples/consul/main.cpp b/external/libhv/libhv-1.3.2/examples/consul/main.cpp new file mode 100644 index 0000000..867f988 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/consul/main.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +#include "consul.h" + +int main(int argc, char* argv[]) { + if (argc < 3) { + printf("Usage: consul_cli subcmd ServiceName [ServiceAddress ServicePort] [NodeIP NodePort]\n"); + printf("subcmd=[register,deregister,discover]\n"); + return -10; + } + const char* subcmd = argv[1]; + const char* ServiceName = argv[2]; + const char* ServiceAddress = "127.0.0.1"; + int ServicePort = 0; + const char* NodeIP = "127.0.0.1"; + int NodePort = 8500; + if (argc > 3) { + ServiceAddress = argv[3]; + } + if (argc > 4) { + ServicePort = atoi(argv[4]); + } + if (argc > 5) { + NodeIP = argv[5]; + } + if (argc > 6) { + NodePort = atoi(argv[6]); + } + + consul_node_t node; + strncpy(node.ip, NodeIP, sizeof(node.ip)); + node.port = NodePort; + + consul_service_t service; + strncpy(service.name, ServiceName, sizeof(service.name)); + strncpy(service.ip, ServiceAddress, sizeof(service.ip)); + service.port = ServicePort; + + consul_health_t health; + + if (strcmp(subcmd, "register") == 0) { + int ret = register_service(&node, &service, &health); + printf("register_service retval=%d\n", ret); + goto discover; + } + else if (strcmp(subcmd, "deregister") == 0) { + int ret = deregister_service(&node, &service); + printf("deregister_service retval=%d\n", ret); + goto discover; + } + else if (strcmp(subcmd, "discover") == 0) { +discover: + std::vector services; + discover_services(&node, ServiceName, services); + for (auto& service : services) { + printf("name=%s ip=%s port=%d\n", service.name, service.ip, service.port); + } + } + else { + printf("subcmd error!\n"); + return -20; + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/curl.cpp b/external/libhv/libhv-1.3.2/examples/curl.cpp new file mode 100644 index 0000000..2a23f3d --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/curl.cpp @@ -0,0 +1,330 @@ +/* + * @build: make examples + * @server bin/httpd -s restart -d + * @usage: bin/curl -v www.baidu.com + * bin/curl -v 127.0.0.1:8080 + * bin/curl -v 127.0.0.1:8080/ping + * bin/curl -v 127.0.0.1:8080/echo -d 'hello,world!' + */ + +#include "HttpClient.h" +#include "hurl.h" + +#ifdef _MSC_VER +#include "misc/win32_getopt.h" +#else +#include +#endif + +static bool verbose = false; +static const char* method = NULL; +static const char* url = "/"; +static int http_version = 1; +static int grpc = 0; +static int send_count = 1; +static int retry_count = 0; +static int retry_delay = 3; +static int timeout = 0; + +static int lopt = 0; +static const char* http_proxy = NULL; +static const char* https_proxy = NULL; +static const char* no_proxy = NULL; + +static const char* options = "hVvX:H:r:d:F:n:"; +static const struct option long_options[] = { + {"help", no_argument, NULL, 'h'}, + {"verion", no_argument, NULL, 'V'}, + {"verbose", no_argument, NULL, 'v'}, + {"method", required_argument, NULL, 'X'}, + {"header", required_argument, NULL, 'H'}, + {"range", required_argument, NULL, 'r'}, + {"data", required_argument, NULL, 'd'}, + {"form", required_argument, NULL, 'F'}, + {"count", required_argument, NULL, 'n'}, + {"http2", no_argument, &http_version, 2}, + {"grpc", no_argument, &grpc, 1}, + \ + {"http-proxy", required_argument, &lopt, 1}, + {"https-proxy", required_argument, &lopt, 2}, + {"no-proxy", required_argument, &lopt, 3}, + {"retry", required_argument, &lopt, 4}, + {"delay", required_argument, &lopt, 5}, + {"timeout", required_argument, &lopt, 6}, + \ + {NULL, 0, NULL, 0} +}; +static const char* help = R"(Options: + -h|--help Print this message. + -V|--version Print version. + -v|--verbose Show verbose infomation. + -X|--method Set http method. + -H|--header Add http header, -H "Content-Type: application/json" + -r|--range Add http header Range:bytes=0-1023 + -d|--data Set http body. + -F|--form Set http form, -F "name=value" -F "file=@filename" + -n|--count Send request count, used for test keep-alive + --http2 Use http2 + --grpc Use grpc over http2 + --http-proxy Set http proxy + --https-proxy Set https proxy + --no-proxy Set no proxy + --retry Set fail retry count + --timeout Set timeout, unit(s) + +Examples: + curl -v GET httpbin.org/get + curl -v POST httpbin.org/post user=admin pswd=123456 + curl -v PUT httpbin.org/put user=admin pswd=123456 + curl -v localhost:8080 + curl -v localhost:8080 -r 0-9 + curl -v localhost:8080/ping + curl -v localhost:8080/query?page_no=1\&page_size=10 + curl -v localhost:8080/echo hello,world! + curl -v localhost:8080/kv user=admin\&pswd=123456 + curl -v localhost:8080/json user=admin pswd=123456 + curl -v localhost:8080/form -F file=@filename + curl -v localhost:8080/upload @filename +)"; + +static void print_usage() { + fprintf(stderr, "Usage: curl [%s] [METHOD] url [header_field:header_value] [body_key=body_value]\n", options); +} +static void print_version() { + fprintf(stderr, "curl version 1.0.0\n"); +} +static void print_help() { + print_usage(); + puts(help); + print_version(); +} + +static bool is_upper_string(const char* str) { + const char* p = str; + while (*p >= 'A' && *p <= 'Z') ++p; + return *p == '\0'; +} + +static int parse_data(char* arg, HttpRequest* req) { + char* pos = NULL; + // @filename + if (arg[0] == '@') { + req->File(arg + 1); + return 0; + } + + // k1=v1&k2=v2 + hv::KeyValue kvs = hv::splitKV(arg, '&', '='); + if (kvs.size() >= 2) { + if (req->ContentType() == CONTENT_TYPE_NONE) { + req->content_type = X_WWW_FORM_URLENCODED; + } + for (auto& kv : kvs) { + req->Set(kv.first.c_str(), kv.second); + } + return 0; + } + + // k=v + if ((pos = strchr(arg, '=')) != NULL) { + *pos = '\0'; + if (pos[1] == '@') { + // file=@filename + req->content_type = MULTIPART_FORM_DATA; + req->SetFormFile(optarg, pos + 2); + } else { + if (req->ContentType() == CONTENT_TYPE_NONE) { + req->content_type = APPLICATION_JSON; + } + req->Set(arg, pos + 1); + } + return 0; + } + + if (req->ContentType() == CONTENT_TYPE_NONE) { + req->content_type = TEXT_PLAIN; + } + req->body = arg; + return 0; +} + +static int parse_cmdline(int argc, char* argv[], HttpRequest* req) { + int opt; + int opt_idx; + char* pos = NULL; + while ((opt = getopt_long(argc, argv, options, long_options, &opt_idx)) != EOF) { + switch(opt) { + case 'h': print_help(); exit(0); + case 'V': print_version(); exit(0); + case 'v': verbose = true; break; + case 'X': method = optarg; break; + case 'H': + // -H "Content-Type: application/json" + pos = strchr(optarg, ':'); + if (pos) { + *pos = '\0'; + req->headers[optarg] = hv::trim(pos + 1); + *pos = ':'; + } + break; + case 'r': + req->headers["Range"] = std::string("bytes=").append(optarg); + break; + case 'd': + parse_data(optarg, req); + break; + case 'F': + pos = strchr(optarg, '='); + if (pos) { + req->content_type = MULTIPART_FORM_DATA; + *pos = '\0'; + if (pos[1] == '@') { + // -F file=@filename + req->SetFormFile(optarg, pos + 2); + } else { + // -F name=value + req->SetFormData(optarg, pos + 1); + } + *pos = '='; + } + break; + case 'n': send_count = atoi(optarg); break; + case 0 : + { + switch (lopt) { + case 1: http_proxy = optarg; break; + case 2: https_proxy = optarg; break; + case 3: no_proxy = optarg; break; + case 4: retry_count = atoi(optarg);break; + case 5: retry_delay = atoi(optarg);break; + case 6: timeout = atoi(optarg);break; + default: break; + } + } + default: break; + } + } + + if (optind == argc) { + fprintf(stderr, "Missing url\n"); + print_usage(); + exit(-1); + } + + if (is_upper_string(argv[optind])) { + method = argv[optind++]; + } + url = argv[optind++]; + + for (int d = optind; d < argc; ++d) { + char* arg = argv[d]; + if ((pos = strchr(arg, ':')) != NULL) { + *pos = '\0'; + req->headers[arg] = pos + 1; + } else { + parse_data(arg, req); + } + } + + // --grpc + if (grpc) { + http_version = 2; + req->content_type = APPLICATION_GRPC; + } + // --http2 + if (http_version == 2) { + req->http_major = 2; + req->http_minor = 0; + } + // --timeout + if (timeout > 0) { + req->timeout = timeout; + } + + return 0; +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + print_usage(); + return 0; + } + + int ret = 0; + HttpRequest req; + parse_cmdline(argc, argv, &req); + if (method) { + req.method = http_method_enum(method); + } else { + req.DumpBody(); + if (req.body.empty()) { + req.method = HTTP_GET; + } else { + req.method = HTTP_POST; + } + } + req.url = HUrl::escapeUrl(url); + req.http_cb = [](HttpMessage* res, http_parser_state state, const char* data, size_t size) { + if (state == HP_HEADERS_COMPLETE) { + if (verbose) { + fprintf(stderr, "%s", res->Dump(true, false).c_str()); + } + } else if (state == HP_BODY) { + if (data && size) { + printf("%.*s", (int)size, data); + // This program no need to save data to body. + // res->body.append(data, size); + } + } + }; + + hv::HttpClient cli; + // http_proxy + if (http_proxy) { + hv::StringList ss = hv::split(http_proxy, ':'); + const char* host = ss[0].c_str(); + int port = ss.size() == 2 ? hv::from_string(ss[1]) : DEFAULT_HTTP_PORT; + fprintf(stderr, "* http_proxy=%s:%d\n", host, port); + cli.setHttpProxy(host, port); + } + // https_proxy + if (https_proxy) { + hv::StringList ss = hv::split(https_proxy, ':'); + const char* host = ss[0].c_str(); + int port = ss.size() == 2 ? hv::from_string(ss[1]) : DEFAULT_HTTPS_PORT; + fprintf(stderr, "* https_proxy=%s:%d\n", host, port); + cli.setHttpsProxy(host, port); + } + // no_proxy + if (no_proxy) { + hv::StringList ss = hv::split(no_proxy, ','); + fprintf(stderr, "* no_proxy="); + for (const auto& s : ss) { + fprintf(stderr, "%s,", s.c_str()); + cli.addNoProxy(s.c_str()); + } + fprintf(stderr, "\n"); + } + +send: + if (verbose) { + fprintf(stderr, "%s\n", req.Dump(true, true).c_str()); + } + HttpResponse res; + ret = cli.send(&req, &res); + if (ret != 0) { + fprintf(stderr, "* Failed:%s:%d\n", http_client_strerror(ret), ret); + if (retry_count > 0) { + fprintf(stderr, "\nretry again later...%d\n", retry_count); + --retry_count; + hv_sleep(retry_delay); + goto send; + } + } + if (--send_count > 0) { + fprintf(stderr, "\nsend again later...%d\n", send_count); + hv_sleep(retry_delay); + goto send; + } + return ret; +} diff --git a/external/libhv/libhv-1.3.2/examples/hloop_test.c b/external/libhv/libhv-1.3.2/examples/hloop_test.c new file mode 100644 index 0000000..8c68552 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/hloop_test.c @@ -0,0 +1,118 @@ +/* + * @build: make examples + * @usage: bin/hloop_test + * bin/nc 127.0.0.1 10514 + * nc 127.0.0.1 10514 + * + */ + +#include "hloop.h" +#include "hbase.h" +#include "hlog.h" +#include "nlog.h" + +void mylogger(int loglevel, const char* buf, int len) { + if (loglevel >= LOG_LEVEL_ERROR) { + stderr_logger(loglevel, buf, len); + } + + if (loglevel >= LOG_LEVEL_INFO) { + file_logger(loglevel, buf, len); + } + + network_logger(loglevel, buf, len); +} + +void on_idle(hidle_t* idle) { + printf("on_idle: event_id=%llu\tpriority=%d\tuserdata=%ld\n", + LLU(hevent_id(idle)), hevent_priority(idle), (long)(intptr_t)(hevent_userdata(idle))); +} + +void on_timer(htimer_t* timer) { + hloop_t* loop = hevent_loop(timer); + printf("on_timer: event_id=%llu\tpriority=%d\tuserdata=%ld\ttime=%llus\thrtime=%lluus\n", + LLU(hevent_id(timer)), hevent_priority(timer), (long)(intptr_t)(hevent_userdata(timer)), + LLU(hloop_now(loop)), LLU(hloop_now_hrtime(loop))); +} + +void cron_minutely(htimer_t* timer) { + time_t now = time(NULL); + printf("cron_minutely: %s\n", ctime(&now)); +} + +void cron_hourly(htimer_t* timer) { + time_t now = time(NULL); + printf("cron_hourly: %s\n", ctime(&now)); +} + +void timer_write_log(htimer_t* timer) { + static int cnt = 0; + hlogd("[%d] Do you recv me?", ++cnt); + hlogi("[%d] Do you recv me?", ++cnt); + hloge("[%d] Do you recv me?", ++cnt); +} + +void on_stdin(hio_t* io, void* buf, int readbytes) { + printf("on_stdin fd=%d readbytes=%d\n", hio_fd(io), readbytes); + printf("> %s\n", (char*)buf); + if (strncmp((char*)buf, "quit", 4) == 0) { + hloop_stop(hevent_loop(io)); + } +} + +void on_custom_events(hevent_t* ev) { + printf("on_custom_events event_type=%d userdata=%ld\n", (int)ev->event_type, (long)(intptr_t)ev->userdata); +} + +int main() { + // memcheck atexit + HV_MEMCHECK; + + hloop_t* loop = hloop_new(0); + + // test idle and priority + for (int i = HEVENT_LOWEST_PRIORITY; i <= HEVENT_HIGHEST_PRIORITY; ++i) { + hidle_t* idle = hidle_add(loop, on_idle, 10); + hevent_set_priority(idle, i); + } + + // test timer timeout + for (int i = 1; i <= 10; ++i) { + htimer_t* timer = htimer_add(loop, on_timer, i*1000, 3); + hevent_set_userdata(timer, (void*)(intptr_t)i); + } + + // test timer period + int minute = time(NULL)%3600/60; + htimer_add_period(loop, cron_minutely, -1, -1, -1, -1, -1, INFINITE); + htimer_add_period(loop, cron_hourly, minute+1, -1, -1, -1, -1, INFINITE); + + // test network_logger + htimer_add(loop, timer_write_log, 1000, INFINITE); + hlog_set_handler(mylogger); + hlog_set_file("loop.log"); + hlog_set_format(DEFAULT_LOG_FORMAT); +#ifndef _MSC_VER + logger_enable_color(hlog, 1); +#endif + nlog_listen(loop, DEFAULT_LOG_PORT); + + // test nonblock stdin + printf("input 'quit' to quit loop\n"); + char buf[64]; + hread(loop, 0, buf, sizeof(buf), on_stdin); + + // test custom_events + for (int i = 0; i < 10; ++i) { + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.event_type = (hevent_type_e)(HEVENT_TYPE_CUSTOM + i); + ev.cb = on_custom_events; + ev.userdata = (void*)(intptr_t)i; + hloop_post_event(loop, &ev); + } + + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/hmain_test.cpp b/external/libhv/libhv-1.3.2/examples/hmain_test.cpp new file mode 100644 index 0000000..886c6f2 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/hmain_test.cpp @@ -0,0 +1,257 @@ +#include "hv.h" +#include "hmain.h" +#include "iniparser.h" + +/* + * @build: make examples + * @usage: bin/hmain_test -h + * bin/hmain_test -v + * + * bin/hmain_test -c etc/hmain_test.conf -d + * ps aux | grep hmain_test + * + * bin/hmain_test -s stop + * ps aux | grep hmain_test + * + */ + +typedef struct conf_ctx_s { + IniParser* parser; + int loglevel; + int worker_processes; + int worker_threads; + int port; +} conf_ctx_t; +conf_ctx_t g_conf_ctx; + +inline void conf_ctx_init(conf_ctx_t* ctx) { + ctx->parser = new IniParser; + ctx->loglevel = LOG_LEVEL_DEBUG; + ctx->worker_processes = 0; + ctx->worker_threads = 0; + ctx->port = 0; +} + +static void print_version(); +static void print_help(); + +static int parse_confile(const char* confile); +static void worker_fn(void* userdata); + +// short options +static const char options[] = "hvc:ts:dp:"; +// long options +static const option_t long_options[] = { + {'h', "help", NO_ARGUMENT}, + {'v', "version", NO_ARGUMENT}, + {'c', "confile", REQUIRED_ARGUMENT}, + {'t', "test", NO_ARGUMENT}, + {'s', "signal", REQUIRED_ARGUMENT}, + {'d', "daemon", NO_ARGUMENT}, + {'p', "port", REQUIRED_ARGUMENT} +}; +static const char detail_options[] = R"( + -h|--help Print this information + -v|--version Print version + -c|--confile Set configure file, default etc/{program}.conf + -t|--test Test configure file and exit + -s|--signal Send to process, + =[start,stop,restart,status,reload] + -d|--daemon Daemonize + -p|--port Set listen port +)"; + +void print_version() { + printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); +} + +void print_help() { + printf("Usage: %s [%s]\n", g_main_ctx.program_name, options); + printf("Options:\n%s\n", detail_options); +} + +int parse_confile(const char* confile) { + int ret = g_conf_ctx.parser->LoadFromFile(confile); + if (ret != 0) { + printf("Load confile [%s] failed: %d\n", confile, ret); + exit(-40); + } + + // logfile + std::string str = g_conf_ctx.parser->GetValue("logfile"); + if (!str.empty()) { + strncpy(g_main_ctx.logfile, str.c_str(), sizeof(g_main_ctx.logfile)); + } + hlog_set_file(g_main_ctx.logfile); + // loglevel + str = g_conf_ctx.parser->GetValue("loglevel"); + if (!str.empty()) { + hlog_set_level_by_str(str.c_str()); + } + // log_filesize + str = g_conf_ctx.parser->GetValue("log_filesize"); + if (!str.empty()) { + hlog_set_max_filesize_by_str(str.c_str()); + } + // log_remain_days + str = g_conf_ctx.parser->GetValue("log_remain_days"); + if (!str.empty()) { + hlog_set_remain_days(atoi(str.c_str())); + } + // log_fsync + str = g_conf_ctx.parser->GetValue("log_fsync"); + if (!str.empty()) { + logger_enable_fsync(hlog, hv_getboolean(str.c_str())); + } + // first log here + hlogi("%s version: %s", g_main_ctx.program_name, hv_compile_version()); + hlog_fsync(); + + // worker_processes + int worker_processes = 0; +#ifdef DEBUG + // Disable multi-processes mode for debugging + worker_processes = 0; +#else + str = g_conf_ctx.parser->GetValue("worker_processes"); + if (str.size() != 0) { + if (strcmp(str.c_str(), "auto") == 0) { + worker_processes = get_ncpu(); + hlogd("worker_processes=ncpu=%d", worker_processes); + } + else { + worker_processes = atoi(str.c_str()); + } + } +#endif + g_conf_ctx.worker_processes = LIMIT(0, worker_processes, MAXNUM_WORKER_PROCESSES); + // worker_threads + int worker_threads = 0; + str = g_conf_ctx.parser->GetValue("worker_threads"); + if (str.size() != 0) { + if (strcmp(str.c_str(), "auto") == 0) { + worker_threads = get_ncpu(); + hlogd("worker_threads=ncpu=%d", worker_threads); + } + else { + worker_threads = atoi(str.c_str()); + } + } + g_conf_ctx.worker_threads = LIMIT(0, worker_threads, 64); + + // port + int port = 0; + const char* szPort = get_arg("p"); + if (szPort) { + port = atoi(szPort); + } + if (port == 0) { + port = g_conf_ctx.parser->Get("port"); + } + if (port == 0) { + printf("Please config listen port!\n"); + exit(-10); + } + g_conf_ctx.port = port; + + hlogi("parse_confile('%s') OK", confile); + return 0; +} + +static void on_reload(void* userdata) { + hlogi("reload confile [%s]", g_main_ctx.confile); + parse_confile(g_main_ctx.confile); +} + +int main(int argc, char** argv) { + // g_main_ctx + main_ctx_init(argc, argv); + if (argc == 1) { + print_help(); + exit(10); + } + // int ret = parse_opt(argc, argv, options); + int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); + if (ret != 0) { + print_help(); + exit(ret); + } + + /* + printf("---------------arg------------------------------\n"); + printf("%s\n", g_main_ctx.cmdline); + for (int i = 0; i < g_main_ctx.arg_kv_size; ++i) { + printf("%s\n", g_main_ctx.arg_kv[i]); + } + for (int i = 0; i < g_main_ctx.arg_list_size; ++i) { + printf("%s\n", g_main_ctx.arg_list[i]); + } + printf("================================================\n"); + + printf("---------------env------------------------------\n"); + for (int i = 0; i < g_main_ctx.envc; ++i) { + printf("%s\n", g_main_ctx.save_envp[i]); + } + printf("================================================\n"); + */ + + // help + if (get_arg("h")) { + print_help(); + exit(0); + } + + // version + if (get_arg("v")) { + print_version(); + exit(0); + } + + // g_conf_ctx + conf_ctx_init(&g_conf_ctx); + const char* confile = get_arg("c"); + if (confile) { + strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile)); + } + parse_confile(g_main_ctx.confile); + + // test + if (get_arg("t")) { + printf("Test confile [%s] OK!\n", g_main_ctx.confile); + exit(0); + } + + // signal + signal_init(on_reload); + const char* signal = get_arg("s"); + if (signal) { + signal_handle(signal); + } + +#ifdef OS_UNIX + // daemon + if (get_arg("d")) { + // nochdir, noclose + int ret = daemon(1, 1); + if (ret != 0) { + printf("daemon error: %d\n", ret); + exit(-10); + } + } +#endif + + // pidfile + create_pidfile(); + + master_workers_run(worker_fn, (void*)(intptr_t)g_conf_ctx.port, g_conf_ctx.worker_processes, g_conf_ctx.worker_threads); + + return 0; +} + +void worker_fn(void* userdata) { + long port = (long)(intptr_t)(userdata); + while (1) { + printf("port=%ld pid=%ld tid=%ld\n", port, hv_getpid(), hv_gettid()); + hv_delay(60000); + } +} diff --git a/external/libhv/libhv-1.3.2/examples/htimer_test.c b/external/libhv/libhv-1.3.2/examples/htimer_test.c new file mode 100644 index 0000000..2272d1b --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/htimer_test.c @@ -0,0 +1,60 @@ +#include "hloop.h" +#include "hbase.h" + +void on_timer(htimer_t* timer) { + printf("time=%llus on_timer\n", LLU(hloop_now(hevent_loop(timer)))); +} + +// test htimer_add +void on_timer_add(htimer_t* timer) { + printf("time=%llus on_timer_add\n", LLU(hloop_now(hevent_loop(timer)))); + htimer_add(hevent_loop(timer), on_timer_add, 1000, 1); +} + +// test htimer_del +void on_timer_del(htimer_t* timer) { + printf("time=%llus on_timer_del\n", LLU(hloop_now(hevent_loop(timer)))); + htimer_del(timer); +} + +// test htimer_reset +void on_timer_reset(htimer_t* timer) { + printf("time=%llus on_timer_reset\n", LLU(hloop_now(hevent_loop(timer)))); + htimer_reset((htimer_t*)hevent_userdata(timer), 0); +} + +// test hloop_stop +void on_timer_quit(htimer_t* timer) { + printf("time=%llus on_timer_quit\n", LLU(hloop_now(hevent_loop(timer)))); + hloop_stop(hevent_loop(timer)); +} + +// test cron +void cron_hourly(htimer_t* timer) { + time_t tt = time(NULL); + printf("time=%llus cron_hourly: %s\n", LLU(hloop_now(hevent_loop(timer))), ctime(&tt)); +} + +int main() { + HV_MEMCHECK; + hloop_t* loop = hloop_new(0); + + htimer_add(loop, on_timer_add, 1000, 1); + htimer_add(loop, on_timer_del, 1000, 10); + htimer_t* reseted = htimer_add(loop, on_timer, 5000, 1); + htimer_t* reset = htimer_add(loop, on_timer_reset, 1000, 5); + hevent_set_userdata(reset, reseted); + + // cron_hourly next triggered in one minute + int minute = time(NULL)%3600/60; + htimer_add_period(loop, cron_hourly, minute+1, -1, -1, -1, -1, INFINITE); + + // quit application after 1 min + htimer_add(loop, on_timer_quit, 60000, 1); + + printf("time=%llus begin\n", LLU(hloop_now(loop))); + hloop_run(loop); + printf("time=%llus stop\n", LLU(hloop_now(loop))); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/http_client_test.cpp b/external/libhv/libhv-1.3.2/examples/http_client_test.cpp new file mode 100644 index 0000000..5d7bbc4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/http_client_test.cpp @@ -0,0 +1,187 @@ +/* + * @build make examples + * + * @server bin/http_server_test 8080 + * + * @client bin/http_client_test + * + */ + +#include "requests.h" +#include "axios.h" +using namespace hv; + +#include "hthread.h" // import hv_gettid + +static void test_http_async_client(HttpClient* cli, int* resp_cnt) { + printf("test_http_async_client request thread tid=%ld\n", hv_gettid()); + auto req = std::make_shared(); + req->method = HTTP_POST; + req->url = "http://127.0.0.1:8080/echo"; + req->headers["Connection"] = "keep-alive"; + req->body = "This is an async request."; + req->timeout = 10; + cli->sendAsync(req, [resp_cnt](const HttpResponsePtr& resp) { + printf("test_http_async_client response thread tid=%ld\n", hv_gettid()); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + *resp_cnt += 1; + }); +} + +static void test_http_sync_client(HttpClient* cli) { + HttpRequest req; + req.method = HTTP_POST; + req.url = "http://127.0.0.1:8080/echo"; + req.headers["Connection"] = "keep-alive"; + req.body = "This is a sync request."; + req.timeout = 10; + HttpResponse resp; + int ret = cli->send(&req, &resp); + if (ret != 0) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp.status_code, resp.status_message()); + printf("%s\n", resp.body.c_str()); + } +} + +static void test_requests() { + // auto resp = requests::get("http://www.example.com"); + // + // make clean && make WITH_OPENSSL=yes + // auto resp = requests::get("https://www.baidu.com"); + + auto resp = requests::get("http://127.0.0.1:8080/ping"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + // Content-Type: application/json + hv::Json jroot; + jroot["user"] = "admin"; + jroot["pswd"] = "123456"; + http_headers headers; + headers["Content-Type"] = "application/json"; + resp = requests::post("http://127.0.0.1:8080/echo", jroot.dump(), headers); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + // Content-Type: multipart/form-data + std::map params; + params["user"] = "admin"; + params["pswd"] = "123456"; + resp = requests::uploadFormFile("http://127.0.0.1:8080/echo", "avatar", "avatar.jpg", params); + if (resp == NULL) { + printf("uploadFormFile failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + /* + size_t filesize = requests::downloadFile("http://www.example.com/index.html", "index.html"); + if (filesize == 0) { + printf("downloadFile failed!\n"); + } else { + printf("downloadFile success!\n"); + } + */ + + // async + /* + // auto req = std::make_shared(); + req->url = "http://127.0.0.1:8080/echo"; + req->method = HTTP_POST; + req->body = "This is an async request."; + req->timeout = 10; + requests::async(req, [](const HttpResponsePtr& resp) { + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + }); + */ +} + +static void test_axios() { + const char* strReq = R"( + { + "method": "POST", + "url": "http://127.0.0.1:8080/echo", + "timeout": 10, + "params": { + "page_no": "1", + "page_size": "10" + }, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "app_id": "123456", + "app_secret": "abcdefg" + } + } + )"; + + // sync + auto resp = axios::axios(strReq); + // auto resp = axios::post("http://127.0.0.1:8080/echo", strReq); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + // async + /* + axios::axios(strReq, [](const HttpResponsePtr& resp) { + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + }); + */ +} + +int main(int argc, char* argv[]) { + int req_cnt = 0; + if (argc > 1) req_cnt = atoi(argv[1]); + if (req_cnt == 0) req_cnt = 1; + + HttpClient sync_client; + HttpClient async_client; + int resp_cnt = 0; + + for (int i = 0; i < req_cnt; ++i) { + test_http_async_client(&async_client, &resp_cnt); + + test_http_sync_client(&sync_client); + + test_requests(); + + test_axios(); + } + + // demo wait async finished + while (resp_cnt < req_cnt) hv_delay(100); + printf("finished!\n"); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/http_server_test.cpp b/external/libhv/libhv-1.3.2/examples/http_server_test.cpp new file mode 100644 index 0000000..2b01c00 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/http_server_test.cpp @@ -0,0 +1,134 @@ +/* + * sample http server + * more detail see examples/httpd + * + */ + +#include "HttpServer.h" +#include "hthread.h" // import hv_gettid +#include "hasync.h" // import hv::async + +using namespace hv; + +/* + * #define TEST_HTTPS 1 + * + * @build ./configure --with-openssl && make clean && make + * + * @server bin/http_server_test 8080 + * + * @client curl -v http://127.0.0.1:8080/ping + * curl -v https://127.0.0.1:8443/ping --insecure + * bin/curl -v http://127.0.0.1:8080/ping + * bin/curl -v https://127.0.0.1:8443/ping + * + */ +#define TEST_HTTPS 0 + +int main(int argc, char** argv) { + HV_MEMCHECK; + + int port = 0; + if (argc > 1) { + port = atoi(argv[1]); + } + if (port == 0) port = 8080; + + HttpService router; + + /* Static file service */ + // curl -v http://ip:port/ + router.Static("/", "./html"); + + /* Forward proxy service */ + router.EnableForwardProxy(); + // curl -v http://httpbin.org/get --proxy http://127.0.0.1:8080 + router.AddTrustProxy("*httpbin.org"); + + /* Reverse proxy service */ + // curl -v http://ip:port/httpbin/get + router.Proxy("/httpbin/", "http://httpbin.org/"); + + /* API handlers */ + // curl -v http://ip:port/ping + router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { + return resp->String("pong"); + }); + + // curl -v http://ip:port/data + router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { + static char data[] = "0123456789"; + return resp->Data(data, 10 /*, false */); + }); + + // curl -v http://ip:port/paths + router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { + return resp->Json(router.Paths()); + }); + + // curl -v http://ip:port/get?env=1 + router.GET("/get", [](const HttpContextPtr& ctx) { + hv::Json resp; + resp["origin"] = ctx->ip(); + resp["url"] = ctx->url(); + resp["args"] = ctx->params(); + resp["headers"] = ctx->headers(); + return ctx->send(resp.dump(2)); + }); + + // curl -v http://ip:port/echo -d "hello,world!" + router.POST("/echo", [](const HttpContextPtr& ctx) { + return ctx->send(ctx->body(), ctx->type()); + }); + + // curl -v http://ip:port/user/123 + router.GET("/user/{id}", [](const HttpContextPtr& ctx) { + hv::Json resp; + resp["id"] = ctx->param("id"); + return ctx->send(resp.dump(2)); + }); + + // curl -v http://ip:port/async + router.GET("/async", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { + writer->Begin(); + writer->WriteHeader("X-Response-tid", hv_gettid()); + writer->WriteHeader("Content-Type", "text/plain"); + writer->WriteBody("This is an async response.\n"); + writer->End(); + }); + + // middleware + router.AllowCORS(); + router.Use([](HttpRequest* req, HttpResponse* resp) { + resp->SetHeader("X-Request-tid", hv::to_string(hv_gettid())); + return HTTP_STATUS_NEXT; + }); + + HttpServer server; + server.service = &router; + server.port = port; +#if TEST_HTTPS + server.https_port = 8443; + hssl_ctx_opt_t param; + memset(¶m, 0, sizeof(param)); + param.crt_file = "cert/server.crt"; + param.key_file = "cert/server.key"; + param.endpoint = HSSL_SERVER; + if (server.newSslCtx(¶m) != 0) { + fprintf(stderr, "new SSL_CTX failed!\n"); + return -20; + } +#endif + + // uncomment to test multi-processes + // server.setProcessNum(4); + // uncomment to test multi-threads + // server.setThreadNum(4); + + server.start(); + + // press Enter to stop + while (getchar() != '\n'); + hv::async::cleanup(); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/httpd/handler.cpp b/external/libhv/libhv-1.3.2/examples/httpd/handler.cpp new file mode 100644 index 0000000..cccc1a3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/httpd/handler.cpp @@ -0,0 +1,370 @@ +#include "handler.h" + +#include // import std::thread +#include // import std::chrono + +#include "hbase.h" +#include "htime.h" +#include "hfile.h" +#include "hstring.h" +#include "EventLoop.h" // import setTimeout, setInterval + +int Handler::preprocessor(HttpRequest* req, HttpResponse* resp) { + // printf("%s:%d\n", req->client_addr.ip.c_str(), req->client_addr.port); + // printf("%s\n", req->Dump(true, true).c_str()); + +#if REDIRECT_HTTP_TO_HTTPS + // 301 + if (req->scheme == "http") { + std::string location = hv::asprintf("https://%s:%d%s", req->host.c_str(), 8443, req->path.c_str()); + return resp->Redirect(location, HTTP_STATUS_MOVED_PERMANENTLY); + } +#endif + + // Unified verification request Content-Type? + // if (req->content_type != APPLICATION_JSON) { + // return response_status(resp, HTTP_STATUS_BAD_REQUEST); + // } + + // Deserialize request body to json, form, etc. + req->ParseBody(); + + // Unified setting response Content-Type? + resp->content_type = APPLICATION_JSON; + + return HTTP_STATUS_NEXT; +} + +int Handler::postprocessor(HttpRequest* req, HttpResponse* resp) { + // printf("%s\n", resp->Dump(true, true).c_str()); + return resp->status_code; +} + +int Handler::errorHandler(const HttpContextPtr& ctx) { + int error_code = ctx->response->status_code; + return response_status(ctx, error_code); +} + +int Handler::Authorization(HttpRequest* req, HttpResponse* resp) { + // authentication sample code + if (strcmp(req->path.c_str(), "/login") == 0) { + return HTTP_STATUS_NEXT; + } + std::string token = req->GetHeader("Authorization"); + if (token.empty()) { + response_status(resp, 10011, "Miss Authorization header!"); + return HTTP_STATUS_UNAUTHORIZED; + } + else if (strcmp(token.c_str(), "abcdefg") != 0) { + response_status(resp, 10012, "Authorization failed!"); + return HTTP_STATUS_UNAUTHORIZED; + } + return HTTP_STATUS_NEXT; +} + +int Handler::sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { + writer->WriteHeader("X-Response-tid", hv_gettid()); + unsigned long long start_ms = gettimeofday_ms(); + writer->response->Set("start_ms", start_ms); + std::string strTime = req->GetParam("t", "1000"); + if (!strTime.empty()) { + int ms = atoi(strTime.c_str()); + if (ms > 0) { + hv_delay(ms); + } + } + unsigned long long end_ms = gettimeofday_ms(); + writer->response->Set("end_ms", end_ms); + writer->response->Set("cost_ms", end_ms - start_ms); + response_status(writer, 0, "OK"); + return 200; +} + +int Handler::setTimeout(const HttpContextPtr& ctx) { + unsigned long long start_ms = gettimeofday_ms(); + ctx->set("start_ms", start_ms); + std::string strTime = ctx->param("t", "1000"); + if (!strTime.empty()) { + int ms = atoi(strTime.c_str()); + if (ms > 0) { + hv::setTimeout(ms, [ctx, start_ms](hv::TimerID timerID){ + unsigned long long end_ms = gettimeofday_ms(); + ctx->set("end_ms", end_ms); + ctx->set("cost_ms", end_ms - start_ms); + response_status(ctx, 0, "OK"); + }); + } + } + return HTTP_STATUS_UNFINISHED; +} + +int Handler::query(const HttpContextPtr& ctx) { + // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] + // ?query => HttpRequest::query_params + for (auto& param : ctx->params()) { + ctx->set(param.first.c_str(), param.second); + } + response_status(ctx, 0, "OK"); + return 200; +} + +int Handler::kv(HttpRequest* req, HttpResponse* resp) { + if (req->content_type != APPLICATION_URLENCODED) { + return response_status(resp, HTTP_STATUS_BAD_REQUEST); + } + resp->content_type = APPLICATION_URLENCODED; + resp->kv = req->GetUrlEncoded(); + resp->SetUrlEncoded("int", 123); + resp->SetUrlEncoded("float", 3.14); + resp->SetUrlEncoded("string", "hello"); + return 200; +} + +int Handler::json(HttpRequest* req, HttpResponse* resp) { + if (req->content_type != APPLICATION_JSON) { + return response_status(resp, HTTP_STATUS_BAD_REQUEST); + } + resp->content_type = APPLICATION_JSON; + resp->json = req->GetJson(); + resp->json["int"] = 123; + resp->json["float"] = 3.14; + resp->json["string"] = "hello"; + return 200; +} + +int Handler::form(HttpRequest* req, HttpResponse* resp) { + if (req->content_type != MULTIPART_FORM_DATA) { + return response_status(resp, HTTP_STATUS_BAD_REQUEST); + } + resp->content_type = MULTIPART_FORM_DATA; + resp->form = req->GetForm(); + resp->SetFormData("int", 123); + resp->SetFormData("float", 3.14); + resp->SetFormData("string", "hello"); + // resp->SetFormFile("file", "test.jpg"); + return 200; +} + +int Handler::grpc(HttpRequest* req, HttpResponse* resp) { + if (req->content_type != APPLICATION_GRPC) { + return response_status(resp, HTTP_STATUS_BAD_REQUEST); + } + // parse protobuf + // ParseFromString(req->body); + // resp->content_type = APPLICATION_GRPC; + // serailize protobuf + // resp->body = SerializeAsString(xxx); + response_status(resp, 0, "OK"); + return 200; +} + +int Handler::test(const HttpContextPtr& ctx) { + ctx->setContentType(ctx->type()); + ctx->set("bool", ctx->get("bool")); + ctx->set("int", ctx->get("int")); + ctx->set("float", ctx->get("float")); + ctx->set("string", ctx->get("string")); + response_status(ctx, 0, "OK"); + return 200; +} + +int Handler::restful(const HttpContextPtr& ctx) { + // RESTful /:field/ => HttpRequest::query_params + // path=/group/:group_name/user/:user_id + std::string group_name = ctx->param("group_name"); + std::string user_id = ctx->param("user_id"); + ctx->set("group_name", group_name); + ctx->set("user_id", user_id); + response_status(ctx, 0, "OK"); + return 200; +} + +int Handler::login(const HttpContextPtr& ctx) { + std::string username = ctx->get("username"); + std::string password = ctx->get("password"); + if (username.empty() || password.empty()) { + response_status(ctx, 10001, "Miss username or password"); + return HTTP_STATUS_BAD_REQUEST; + } + else if (strcmp(username.c_str(), "admin") != 0) { + response_status(ctx, 10002, "Username not exist"); + return HTTP_STATUS_BAD_REQUEST; + } + else if (strcmp(password.c_str(), "123456") != 0) { + response_status(ctx, 10003, "Password wrong"); + return HTTP_STATUS_BAD_REQUEST; + } + else { + ctx->set("token", "abcdefg"); + response_status(ctx, 0, "OK"); + return HTTP_STATUS_OK; + } +} + +int Handler::upload(const HttpContextPtr& ctx) { + int status_code = 200; + std::string save_path = "html/uploads/"; + if (ctx->is(MULTIPART_FORM_DATA)) { + status_code = ctx->request->SaveFormFile("file", save_path.c_str()); + } else { + std::string filename = ctx->param("filename", "unnamed.txt"); + std::string filepath = save_path + filename; + status_code = ctx->request->SaveFile(filepath.c_str()); + } + return response_status(ctx, status_code); +} + +int Handler::recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size) { + // printf("recvLargeFile state=%d\n", (int)state); + int status_code = HTTP_STATUS_UNFINISHED; + HFile* file = (HFile*)ctx->userdata; + switch (state) { + case HP_HEADERS_COMPLETE: + { + if (ctx->is(MULTIPART_FORM_DATA)) { + // NOTE: You can use multipart_parser if you want to use multipart/form-data. + ctx->close(); + return HTTP_STATUS_BAD_REQUEST; + } + std::string save_path = "html/uploads/"; + std::string filename = ctx->param("filename", "unnamed.txt"); + std::string filepath = save_path + filename; + file = new HFile; + if (file->open(filepath.c_str(), "wb") != 0) { + ctx->close(); + return HTTP_STATUS_INTERNAL_SERVER_ERROR; + } + ctx->userdata = file; + } + break; + case HP_BODY: + { + if (file && data && size) { + if (file->write(data, size) != size) { + ctx->close(); + return HTTP_STATUS_INTERNAL_SERVER_ERROR; + } + } + } + break; + case HP_MESSAGE_COMPLETE: + { + status_code = HTTP_STATUS_OK; + ctx->setContentType(APPLICATION_JSON); + response_status(ctx, status_code); + if (file) { + delete file; + ctx->userdata = NULL; + } + } + break; + case HP_ERROR: + { + if (file) { + file->remove(); + delete file; + ctx->userdata = NULL; + } + } + break; + default: + break; + } + return status_code; +} + +int Handler::sendLargeFile(const HttpContextPtr& ctx) { + std::thread([ctx](){ + ctx->writer->Begin(); + std::string filepath = ctx->service->document_root + ctx->request->Path(); + HFile file; + if (file.open(filepath.c_str(), "rb") != 0) { + ctx->writer->WriteStatus(HTTP_STATUS_NOT_FOUND); + ctx->writer->WriteHeader("Content-Type", "text/html"); + ctx->writer->WriteBody("

404 Not Found

"); + ctx->writer->End(); + return; + } + http_content_type content_type = CONTENT_TYPE_NONE; + const char* suffix = hv_suffixname(filepath.c_str()); + if (suffix) { + content_type = http_content_type_enum_by_suffix(suffix); + } + if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) { + content_type = APPLICATION_OCTET_STREAM; + } + size_t filesize = file.size(); + ctx->writer->WriteHeader("Content-Type", http_content_type_str(content_type)); +#if USE_TRANSFER_ENCODING_CHUNKED + ctx->writer->WriteHeader("Transfer-Encoding", "chunked"); +#else + ctx->writer->WriteHeader("Content-Length", filesize); +#endif + ctx->writer->EndHeaders(); + + char* buf = NULL; + int len = 40960; // 40K + SAFE_ALLOC(buf, len); + size_t total_readbytes = 0; + int last_progress = 0; + int sleep_ms_per_send = 0; + if (ctx->service->limit_rate <= 0) { + // unlimited + } else { + sleep_ms_per_send = len * 1000 / 1024 / ctx->service->limit_rate; + } + if (sleep_ms_per_send == 0) sleep_ms_per_send = 1; + int sleep_ms = sleep_ms_per_send; + auto start_time = std::chrono::steady_clock::now(); + auto end_time = start_time; + while (total_readbytes < filesize) { + if (!ctx->writer->isConnected()) { + break; + } + if (!ctx->writer->isWriteComplete()) { + hv_delay(1); + continue; + } + size_t readbytes = file.read(buf, len); + if (readbytes <= 0) { + // read file error! + ctx->writer->close(); + break; + } + int nwrite = ctx->writer->WriteBody(buf, readbytes); + if (nwrite < 0) { + // disconnected! + break; + } + total_readbytes += readbytes; + int cur_progress = total_readbytes * 100 / filesize; + if (cur_progress > last_progress) { + // printf("<< %s progress: %ld/%ld = %d%%\n", + // ctx->request->path.c_str(), (long)total_readbytes, (long)filesize, (int)cur_progress); + last_progress = cur_progress; + } + end_time += std::chrono::milliseconds(sleep_ms); + std::this_thread::sleep_until(end_time); + } + ctx->writer->End(); + SAFE_FREE(buf); + // auto elapsed_time = std::chrono::duration_cast(end_time - start_time); + // printf("<< %s taked %ds\n", ctx->request->path.c_str(), (int)elapsed_time.count()); + }).detach(); + return HTTP_STATUS_UNFINISHED; +} + +int Handler::sse(const HttpContextPtr& ctx) { + // SSEvent(message) every 1s + hv::setInterval(1000, [ctx](hv::TimerID timerID) { + if (ctx->writer->isConnected()) { + char szTime[DATETIME_FMT_BUFLEN] = {0}; + datetime_t now = datetime_now(); + datetime_fmt(&now, szTime); + ctx->writer->SSEvent(szTime); + } else { + hv::killTimer(timerID); + } + }); + return HTTP_STATUS_UNFINISHED; +} diff --git a/external/libhv/libhv-1.3.2/examples/httpd/handler.h b/external/libhv/libhv-1.3.2/examples/httpd/handler.h new file mode 100644 index 0000000..40f2689 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/httpd/handler.h @@ -0,0 +1,56 @@ +#ifndef HV_HTTPD_HANDLER_H +#define HV_HTTPD_HANDLER_H + +#include "HttpService.h" + +class Handler { +public: + // preprocessor => middleware -> handlers => postprocessor + static int preprocessor(HttpRequest* req, HttpResponse* resp); + static int postprocessor(HttpRequest* req, HttpResponse* resp); + static int errorHandler(const HttpContextPtr& ctx); + + // middleware + static int Authorization(HttpRequest* req, HttpResponse* resp); + + static int sleep(const HttpRequestPtr& req, const HttpResponseWriterPtr& writer); + static int setTimeout(const HttpContextPtr& ctx); + static int query(const HttpContextPtr& ctx); + + static int kv(HttpRequest* req, HttpResponse* resp); + static int json(HttpRequest* req, HttpResponse* resp); + static int form(HttpRequest* req, HttpResponse* resp); + static int grpc(HttpRequest* req, HttpResponse* resp); + + static int test(const HttpContextPtr& ctx); + static int restful(const HttpContextPtr& ctx); + + static int login(const HttpContextPtr& ctx); + static int upload(const HttpContextPtr& ctx); + // SSE: Server Send Events + static int sse(const HttpContextPtr& ctx); + + // LargeFile + static int sendLargeFile(const HttpContextPtr& ctx); + static int recvLargeFile(const HttpContextPtr& ctx, http_parser_state state, const char* data, size_t size); + +private: + static int response_status(HttpResponse* resp, int code = 200, const char* message = NULL) { + if (message == NULL) message = http_status_str((enum http_status)code); + resp->Set("code", code); + resp->Set("message", message); + return code; + } + static int response_status(const HttpResponseWriterPtr& writer, int code = 200, const char* message = NULL) { + response_status(writer->response.get(), code, message); + writer->End(); + return code; + } + static int response_status(const HttpContextPtr& ctx, int code = 200, const char* message = NULL) { + response_status(ctx->response.get(), code, message); + ctx->send(); + return code; + } +}; + +#endif // HV_HTTPD_HANDLER_H diff --git a/external/libhv/libhv-1.3.2/examples/httpd/httpd.cpp b/external/libhv/libhv-1.3.2/examples/httpd/httpd.cpp new file mode 100644 index 0000000..443a0a8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/httpd/httpd.cpp @@ -0,0 +1,352 @@ +#include "hv.h" +#include "hssl.h" +#include "hmain.h" +#include "iniparser.h" + +#include "HttpServer.h" +#include "hasync.h" // import hv::async + +#include "router.h" + +hv::HttpServer g_http_server; +hv::HttpService g_http_service; + +static void print_version(); +static void print_help(); + +static int parse_confile(const char* confile); + +// short options +static const char options[] = "hvc:ts:dp:"; +// long options +static const option_t long_options[] = { + {'h', "help", NO_ARGUMENT}, + {'v', "version", NO_ARGUMENT}, + {'c', "confile", REQUIRED_ARGUMENT}, + {'t', "test", NO_ARGUMENT}, + {'s', "signal", REQUIRED_ARGUMENT}, + {'d', "daemon", NO_ARGUMENT}, + {'p', "port", REQUIRED_ARGUMENT} +}; +static const char detail_options[] = R"( + -h|--help Print this information + -v|--version Print version + -c|--confile Set configure file, default etc/{program}.conf + -t|--test Test configure file and exit + -s|--signal Send to process, + =[start,stop,restart,status,reload] + -d|--daemon Daemonize + -p|--port Set listen port +)"; + +void print_version() { + printf("%s version %s\n", g_main_ctx.program_name, hv_compile_version()); +} + +void print_help() { + printf("Usage: %s [%s]\n", g_main_ctx.program_name, options); + printf("Options:\n%s\n", detail_options); +} + +int parse_confile(const char* confile) { + IniParser ini; + int ret = ini.LoadFromFile(confile); + if (ret != 0) { + printf("Load confile [%s] failed: %d\n", confile, ret); + exit(-40); + } + + // logfile + std::string str = ini.GetValue("logfile"); + if (!str.empty()) { + strncpy(g_main_ctx.logfile, str.c_str(), sizeof(g_main_ctx.logfile)); + } + hlog_set_file(g_main_ctx.logfile); + // loglevel + str = ini.GetValue("loglevel"); + if (!str.empty()) { + hlog_set_level_by_str(str.c_str()); + } + // log_filesize + str = ini.GetValue("log_filesize"); + if (!str.empty()) { + hlog_set_max_filesize_by_str(str.c_str()); + } + // log_remain_days + str = ini.GetValue("log_remain_days"); + if (!str.empty()) { + hlog_set_remain_days(atoi(str.c_str())); + } + // log_fsync + str = ini.GetValue("log_fsync"); + if (!str.empty()) { + logger_enable_fsync(hlog, hv_getboolean(str.c_str())); + } + hlogi("%s version: %s", g_main_ctx.program_name, hv_compile_version()); + hlog_fsync(); + + // worker_processes + int worker_processes = 0; +#ifdef DEBUG + // Disable multi-processes mode for debugging + worker_processes = 0; +#else + str = ini.GetValue("worker_processes"); + if (str.size() != 0) { + if (strcmp(str.c_str(), "auto") == 0) { + worker_processes = get_ncpu(); + hlogd("worker_processes=ncpu=%d", worker_processes); + } + else { + worker_processes = atoi(str.c_str()); + } + } +#endif + g_http_server.worker_processes = LIMIT(0, worker_processes, MAXNUM_WORKER_PROCESSES); + // worker_threads + int worker_threads = 0; + str = ini.GetValue("worker_threads"); + if (str.size() != 0) { + if (strcmp(str.c_str(), "auto") == 0) { + worker_threads = get_ncpu(); + hlogd("worker_threads=ncpu=%d", worker_threads); + } + else { + worker_threads = atoi(str.c_str()); + } + } + g_http_server.worker_threads = LIMIT(0, worker_threads, 64); + + // worker_connections + str = ini.GetValue("worker_connections"); + if (str.size() != 0) { + g_http_server.worker_connections = atoi(str.c_str()); + } + + // http_port + int port = 0; + const char* szPort = get_arg("p"); + if (szPort) { + port = atoi(szPort); + } + if (port == 0) { + port = ini.Get("port"); + } + if (port == 0) { + port = ini.Get("http_port"); + } + g_http_server.port = port; + // https_port + if (HV_WITH_SSL) { + g_http_server.https_port = ini.Get("https_port"); + } + if (g_http_server.port == 0 && g_http_server.https_port == 0) { + printf("Please config listen port!\n"); + exit(-10); + } + + // base_url + str = ini.GetValue("base_url"); + if (str.size() != 0) { + g_http_service.base_url = str; + } + // document_root + str = ini.GetValue("document_root"); + if (str.size() != 0) { + g_http_service.document_root = str; + } + // home_page + str = ini.GetValue("home_page"); + if (str.size() != 0) { + g_http_service.home_page = str; + } + // error_page + str = ini.GetValue("error_page"); + if (str.size() != 0) { + g_http_service.error_page = str; + } + // index_of + str = ini.GetValue("index_of"); + if (str.size() != 0) { + g_http_service.index_of = str; + } + // keepalive_timeout + str = ini.GetValue("keepalive_timeout"); + if (str.size() != 0) { + g_http_service.keepalive_timeout = atoi(str.c_str()); + } + // limit_rate + str = ini.GetValue("limit_rate"); + if (str.size() != 0) { + g_http_service.limit_rate = atoi(str.c_str()); + } + // access_log + str = ini.GetValue("access_log"); + if (str.size() != 0) { + g_http_service.enable_access_log = hv_getboolean(str.c_str()); + } + // cors + if (ini.Get("cors")) { + g_http_service.AllowCORS(); + } + // ssl + if (g_http_server.https_port > 0) { + std::string crt_file = ini.GetValue("ssl_certificate"); + std::string key_file = ini.GetValue("ssl_privatekey"); + std::string ca_file = ini.GetValue("ssl_ca_certificate"); + hlogi("SSL backend is %s", hssl_backend()); + hssl_ctx_opt_t param; + memset(¶m, 0, sizeof(param)); + param.crt_file = crt_file.c_str(); + param.key_file = key_file.c_str(); + param.ca_file = ca_file.c_str(); + param.endpoint = HSSL_SERVER; + if (g_http_server.newSslCtx(¶m) != 0) { +#ifdef OS_WIN + if (strcmp(hssl_backend(), "schannel") == 0) { + hlogw("schannel needs pkcs12 formatted certificate file."); + g_http_server.https_port = 0; + } +#else + hloge("SSL certificate verify failed!"); + exit(0); +#endif + } + else { + hlogi("SSL certificate verify ok!"); + } + } + // proxy + auto proxy_keys = ini.GetKeys("proxy"); + for (const auto& proxy_key : proxy_keys) { + str = ini.GetValue(proxy_key, "proxy"); + if (str.empty()) continue; + if (proxy_key[0] == '/') { + // reverse proxy + const std::string& path = proxy_key; + std::string proxy_url = hv::ltrim(str, "> "); + hlogi("reverse_proxy %s => %s", path.c_str(), proxy_url.c_str()); + g_http_service.Proxy(path.c_str(), proxy_url.c_str()); + } + else if (strcmp(proxy_key.c_str(), "proxy_connect_timeout") == 0) { + g_http_service.proxy_connect_timeout = atoi(str.c_str()); + } + else if (strcmp(proxy_key.c_str(), "proxy_read_timeout") == 0) { + g_http_service.proxy_read_timeout = atoi(str.c_str()); + } + else if (strcmp(proxy_key.c_str(), "proxy_write_timeout") == 0) { + g_http_service.proxy_write_timeout = atoi(str.c_str()); + } + else if (strcmp(proxy_key.c_str(), "forward_proxy") == 0) { + hlogi("forward_proxy = %s", str.c_str()); + if (hv_getboolean(str.c_str())) { + g_http_service.EnableForwardProxy(); + } + } + else if (strcmp(proxy_key.c_str(), "trust_proxies") == 0) { + auto trust_proxies = hv::split(str, ';'); + for (auto trust_proxy : trust_proxies) { + trust_proxy = hv::trim(trust_proxy); + if (trust_proxy.empty()) continue; + hlogi("trust_proxy %s", trust_proxy.c_str()); + g_http_service.AddTrustProxy(trust_proxy.c_str()); + } + } + else if (strcmp(proxy_key.c_str(), "no_proxies") == 0) { + auto no_proxies = hv::split(str, ';'); + for (auto no_proxy : no_proxies) { + no_proxy = hv::trim(no_proxy); + if (no_proxy.empty()) continue; + hlogi("no_proxy %s", no_proxy.c_str()); + g_http_service.AddNoProxy(no_proxy.c_str()); + } + } + } + + hlogi("parse_confile('%s') OK", confile); + return 0; +} + +static void on_reload(void* userdata) { + hlogi("reload confile [%s]", g_main_ctx.confile); + parse_confile(g_main_ctx.confile); +} + +int main(int argc, char** argv) { + // g_main_ctx + main_ctx_init(argc, argv); + //int ret = parse_opt(argc, argv, options); + int ret = parse_opt_long(argc, argv, long_options, ARRAY_SIZE(long_options)); + if (ret != 0) { + print_help(); + exit(ret); + } + + // help + if (get_arg("h")) { + print_help(); + exit(0); + } + + // version + if (get_arg("v")) { + print_version(); + exit(0); + } + + // parse_confile + const char* confile = get_arg("c"); + if (confile) { + strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile)); + } + parse_confile(g_main_ctx.confile); + + // test + if (get_arg("t")) { + printf("Test confile [%s] OK!\n", g_main_ctx.confile); + exit(0); + } + + // signal + signal_init(on_reload); + const char* signal = get_arg("s"); + if (signal) { + signal_handle(signal); + } + +#ifdef OS_UNIX + // daemon + if (get_arg("d")) { + // nochdir, noclose + int ret = daemon(1, 1); + if (ret != 0) { + printf("daemon error: %d\n", ret); + exit(-10); + } + } +#endif + + // pidfile + create_pidfile(); + + // http_server + Router::Register(g_http_service); + g_http_server.registerHttpService(&g_http_service); + +#if 0 + std::atomic_flag init_flag = ATOMIC_FLAG_INIT; + g_http_server.onWorkerStart = [&init_flag](){ + if (!init_flag.test_and_set()) { + hv::async::startup(); + } + }; + g_http_server.onWorkerStop = [&init_flag](){ + if (init_flag.test_and_set()) { + hv::async::cleanup(); + } + }; +#endif + + g_http_server.run(); + return ret; +} diff --git a/external/libhv/libhv-1.3.2/examples/httpd/router.cpp b/external/libhv/libhv-1.3.2/examples/httpd/router.cpp new file mode 100644 index 0000000..046b05a --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/httpd/router.cpp @@ -0,0 +1,148 @@ +#include "router.h" + +#include "handler.h" +#include "hthread.h" // import hv_gettid +#include "hasync.h" // import hv::async +#include "requests.h" // import requests::async + +void Router::Register(hv::HttpService& router) { + /* handler chain */ + // preprocessor -> middleware -> processor -> postprocessor + // processor: pathHandlers -> staticHandler -> errorHandler + router.preprocessor = Handler::preprocessor; + router.postprocessor = Handler::postprocessor; + // router.errorHandler = Handler::errorHandler; + // router.largeFileHandler = Handler::sendLargeFile; + + // middleware + // router.Use(Handler::Authorization); + + // curl -v http://ip:port/ping + router.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { + return resp->String("pong"); + }); + + // curl -v http://ip:port/data + router.GET("/data", [](HttpRequest* req, HttpResponse* resp) { + static char data[] = "0123456789"; + return resp->Data(data, 10 /*, false */); + }); + + // curl -v http://ip:port/html/index.html + router.GET("/html/index.html", [](HttpRequest* req, HttpResponse* resp) { + return resp->File("html/index.html"); + }); + + // curl -v http://ip:port/paths + router.GET("/paths", [&router](HttpRequest* req, HttpResponse* resp) { + return resp->Json(router.Paths()); + }); + + // curl -v http://ip:port/service + router.GET("/service", [](const HttpContextPtr& ctx) { + ctx->setContentType("application/json"); + ctx->set("base_url", ctx->service->base_url); + ctx->set("document_root", ctx->service->document_root); + ctx->set("home_page", ctx->service->home_page); + ctx->set("error_page", ctx->service->error_page); + ctx->set("index_of", ctx->service->index_of); + return 200; + }); + + // curl -v http://ip:port/get?env=1 + router.GET("/get", [](const HttpContextPtr& ctx) { + hv::Json resp; + resp["origin"] = ctx->ip(); + resp["url"] = ctx->url(); + resp["args"] = ctx->params(); + resp["headers"] = ctx->headers(); + return ctx->send(resp.dump(2)); + }); + + // curl -v http://ip:port/echo -d "hello,world!" + router.POST("/echo", [](const HttpContextPtr& ctx) { + return ctx->send(ctx->body(), ctx->type()); + }); + + // wildcard * + // curl -v http://ip:port/wildcard/any + router.GET("/wildcard*", [](HttpRequest* req, HttpResponse* resp) { + std::string str = req->path + " match /wildcard*"; + return resp->String(str); + }); + + // curl -v http://ip:port/async + router.GET("/async", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { + writer->Begin(); + writer->WriteHeader("X-Response-tid", hv_gettid()); + writer->WriteHeader("Content-Type", "text/plain"); + writer->WriteBody("This is an async response.\n"); + writer->End(); + }); + + // curl -v http://ip:port/www.* + // curl -v http://ip:port/www.example.com + router.GET("/www.*", [](const HttpRequestPtr& req, const HttpResponseWriterPtr& writer) { + auto req2 = std::make_shared(); + req2->url = req->path.substr(1); + requests::async(req2, [writer](const HttpResponsePtr& resp2){ + writer->Begin(); + if (resp2 == NULL) { + writer->WriteStatus(HTTP_STATUS_NOT_FOUND); + writer->WriteHeader("Content-Type", "text/html"); + writer->WriteBody("

404 Not Found

"); + } else { + writer->WriteResponse(resp2.get()); + } + writer->End(); + }); + }); + + // curl -v http://ip:port/sleep?t=1000 + router.GET("/sleep", Handler::sleep); + + // curl -v http://ip:port/setTimeout?t=1000 + router.GET("/setTimeout", Handler::setTimeout); + + // curl -v http://ip:port/query?page_no=1\&page_size=10 + router.GET("/query", Handler::query); + + // Content-Type: application/x-www-form-urlencoded + // curl -v http://ip:port/kv -H "content-type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' + router.POST("/kv", Handler::kv); + + // Content-Type: application/json + // curl -v http://ip:port/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' + router.POST("/json", Handler::json); + + // Content-Type: multipart/form-data + // bin/curl -v http://ip:port/form -F 'user=admin' -F 'pswd=123456' + router.POST("/form", Handler::form); + + // curl -v http://ip:port/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' + // curl -v http://ip:port/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' + // bin/curl -v http://ip:port/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' + router.POST("/test", Handler::test); + + // Content-Type: application/grpc + // bin/curl -v --http2 http://ip:port/grpc -H "content-type:application/grpc" -d 'protobuf' + router.POST("/grpc", Handler::grpc); + + // RESTful API: /group/:group_name/user/:user_id + // curl -v -X DELETE http://ip:port/group/test/user/123 + router.Delete("/group/:group_name/user/:user_id", Handler::restful); + // router.Delete("/group/{group_name}/user/{user_id}", Handler::restful); + + // curl -v http://ip:port/login -H "Content-Type:application/json" -d '{"username":"admin","password":"123456"}' + router.POST("/login", Handler::login); + + // curl -v http://ip:port/upload?filename=LICENSE -d '@LICENSE' + // curl -v http://ip:port/upload -F 'file=@LICENSE' + router.POST("/upload", Handler::upload); + // curl -v http://ip:port/upload/README.md -d '@README.md' + router.POST("/upload/{filename}", Handler::recvLargeFile); + + // SSE: Server Send Events + // @test html/EventSource.html EventSource.onmessage + router.GET("/sse", Handler::sse); +} diff --git a/external/libhv/libhv-1.3.2/examples/httpd/router.h b/external/libhv/libhv-1.3.2/examples/httpd/router.h new file mode 100644 index 0000000..ac6450e --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/httpd/router.h @@ -0,0 +1,11 @@ +#ifndef HV_HTTPD_ROUTER_H +#define HV_HTTPD_ROUTER_H + +#include "HttpService.h" + +class Router { +public: + static void Register(hv::HttpService& router); +}; + +#endif // HV_HTTPD_ROUTER_H diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.c b/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.c new file mode 100644 index 0000000..030311c --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.c @@ -0,0 +1,3110 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + 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. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 14) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if (!(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + if (strlen(valuestring) <= strlen(object->valuestring)) + { + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + } + + if (printed != NULL) + { + hooks->deallocate(printed); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF)) || cJSON_IsInvalid(a)) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.h b/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.h new file mode 100644 index 0000000..e97e5f4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/cJSON.h @@ -0,0 +1,293 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + 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. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 14 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable adress area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/handler.h b/external/libhv/libhv-1.3.2/examples/jsonrpc/handler.h new file mode 100644 index 0000000..18d1a1d --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/handler.h @@ -0,0 +1,82 @@ +#ifndef HV_JSON_RPC_HANDLER_H_ +#define HV_JSON_RPC_HANDLER_H_ + +#include "router.h" + +void error_response(cJSON* jres, int code, const char* message) { + cJSON* jerror = cJSON_CreateObject(); + cJSON_AddItemToObject(jerror, "code", cJSON_CreateNumber(code)); + cJSON_AddItemToObject(jerror, "message", cJSON_CreateString(message)); + cJSON_AddItemToObject(jres, "error", jerror); +} + +void not_found(cJSON* jreq, cJSON* jres) { + error_response(jres, 404, "Not Found"); +} + +void bad_request(cJSON* jreq, cJSON* jres) { + error_response(jres, 400, "Bad Request"); +} + +void calc_add(cJSON* jreq, cJSON* jres) { + cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); + if (cJSON_GetArraySize(jparams) != 2) { + bad_request(jreq, jres); + return; + } + cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); + int num1 = cJSON_GetNumberValue(jnum1); + cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); + int num2 = cJSON_GetNumberValue(jnum2); + int result = num1 + num2; + cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); +} + +void calc_sub(cJSON* jreq, cJSON* jres) { + cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); + if (cJSON_GetArraySize(jparams) != 2) { + bad_request(jreq, jres); + return; + } + cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); + int num1 = cJSON_GetNumberValue(jnum1); + cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); + int num2 = cJSON_GetNumberValue(jnum2); + int result = num1 - num2; + cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); +} + +void calc_mul(cJSON* jreq, cJSON* jres) { + cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); + if (cJSON_GetArraySize(jparams) != 2) { + bad_request(jreq, jres); + return; + } + cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); + int num1 = cJSON_GetNumberValue(jnum1); + cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); + int num2 = cJSON_GetNumberValue(jnum2); + int result = num1 * num2; + cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); +} + +void calc_div(cJSON* jreq, cJSON* jres) { + cJSON* jparams = cJSON_GetObjectItem(jreq, "params"); + if (cJSON_GetArraySize(jparams) != 2) { + bad_request(jreq, jres); + return; + } + cJSON* jnum1 = cJSON_GetArrayItem(jparams, 0); + int num1 = cJSON_GetNumberValue(jnum1); + cJSON* jnum2 = cJSON_GetArrayItem(jparams, 1); + int num2 = cJSON_GetNumberValue(jnum2); + if (num2 == 0) { + bad_request(jreq, jres); + return; + } else { + int result = num1 / num2; + cJSON_AddItemToObject(jres, "result", cJSON_CreateNumber(result)); + } +} + +#endif // HV_JSON_RPC_ROUTER_H_ diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_client.c b/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_client.c new file mode 100644 index 0000000..82d8c67 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_client.c @@ -0,0 +1,136 @@ +/* + * json rpc client + * + * @build make jsonrpc + * @server bin/jsonrpc_server 1234 + * @client bin/jsonrpc_client 127.0.0.1 1234 add 1 2 + * + */ + +#include "hloop.h" +#include "hatomic.h" +#include "hbase.h" +#include "hsocket.h" + +#include "cJSON.h" + +// hloop_create_tcp_client -> on_connect -> hio_write -> hio_read -> on_recv + +static int verbose = 0; +static unpack_setting_t jsonrpc_unpack_setting; + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + cJSON* jreq = (cJSON*)(hevent_userdata(io)); + if (jreq) { + cJSON_Delete(jreq); + hevent_set_userdata(io, NULL); + } + + hloop_stop(hevent_loop(io)); +} + +static void on_recv(hio_t* io, void* readbuf, int readbytes) { + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + + char* resp_str = (char*)readbuf; + printf("< %s\n", resp_str); + // cJSON_Parse + cJSON* jres = cJSON_Parse(resp_str); + cJSON* jerror = cJSON_GetObjectItem(jres, "error"); + cJSON* jresult = cJSON_GetObjectItem(jres, "result"); + // ... + cJSON_Delete(jres); + + hio_close(io); +} + +static void on_connect(hio_t* io) { + printf("on_connect fd=%d\n", hio_fd(io)); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("connect connfd=%d [%s] => [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + + hio_setcb_read(io, on_recv); + hio_set_unpack(io, &jsonrpc_unpack_setting); + hio_read(io); + + cJSON* jreq = (cJSON*)(hevent_userdata(io)); + hevent_set_userdata(io, NULL); + assert(jreq != NULL); + + // cJSON_Print -> hio_write + char* req_str = cJSON_PrintUnformatted(jreq); + printf("> %s\n", req_str); + // NOTE: +1 for \0 + hio_write(io, req_str, strlen(req_str) + 1); + + cJSON_Delete(jreq); + cJSON_free(req_str); +} + +static int jsonrpc_call(hloop_t* loop, const char* host, int port, const char* method, const char* param1, const char* param2) { + hio_t* connio = hio_create_socket(loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (connio == NULL) { + return -1; + } + // printf("connfd=%d\n", hio_fd(connio)); + + // construct request + cJSON* jreq = cJSON_CreateObject(); + static hatomic_t s_id = HATOMIC_VAR_INIT(0); + cJSON_AddItemToObject(jreq, "id", cJSON_CreateNumber(++s_id)); + cJSON_AddItemToObject(jreq, "method", cJSON_CreateString(method)); + cJSON* jparams = cJSON_CreateArray(); + cJSON_AddItemToArray(jparams, cJSON_CreateNumber(atoi(param1))); + cJSON_AddItemToArray(jparams, cJSON_CreateNumber(atoi(param2))); + cJSON_AddItemToObject(jreq, "params", jparams); + hevent_set_userdata(connio, jreq); + + hio_setcb_connect(connio, on_connect); + hio_setcb_close(connio, on_close); + hio_connect(connio); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 6) { + printf("Usage: %s host port method param1 param2\n", argv[0]); + printf("method = [add, sub, mul, div]\n"); + printf("Examples:\n"); + printf(" %s 127.0.0.1 1234 add 1 2\n", argv[0]); + printf(" %s 127.0.0.1 1234 div 1 0\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + const char* method = argv[3]; + const char* param1 = argv[4]; + const char* param2 = argv[5]; + + // init jsonrpc_unpack_setting + memset(&jsonrpc_unpack_setting, 0, sizeof(unpack_setting_t)); + jsonrpc_unpack_setting.mode = UNPACK_BY_DELIMITER; + jsonrpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + jsonrpc_unpack_setting.delimiter[0] = '\0'; + jsonrpc_unpack_setting.delimiter_bytes = 1; + + hloop_t* loop = hloop_new(0); + + jsonrpc_call(loop, host, port, method, param1, param2); + + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_server.c b/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_server.c new file mode 100644 index 0000000..b21af91 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/jsonrpc_server.c @@ -0,0 +1,123 @@ +/* + * json rpc server + * + * @build make jsonrpc + * @server bin/jsonrpc_server 1234 + * @client bin/jsonrpc_client 127.0.0.1 1234 add 1 2 + * + */ + +#include "hloop.h" +#include "hbase.h" +#include "hsocket.h" + +#include "cJSON.h" +#include "router.h" +#include "handler.h" + +// hloop_create_tcp_server -> on_accept -> hio_read -> on_recv -> hio_write + +static int verbose = 0; +static unpack_setting_t jsonrpc_unpack_setting; + +jsonrpc_router router[] = { + {"add", calc_add}, + {"sub", calc_sub}, + {"mul", calc_mul}, + {"div", calc_div}, +}; +#define JSONRPC_ROUTER_NUM (sizeof(router)/sizeof(router[0])) + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); +} + +static void on_recv(hio_t* io, void* readbuf, int readbytes) { + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + + // cJSON_Parse -> router -> cJSON_Print -> hio_write + char* req_str = (char*)readbuf; + printf("> %s\n", req_str); + cJSON* jreq = cJSON_Parse(req_str); + cJSON* jres = cJSON_CreateObject(); + cJSON* jid = cJSON_GetObjectItem(jreq, "id"); + cJSON* jmethod = cJSON_GetObjectItem(jreq, "method"); + if (cJSON_IsNumber(jid)) { + long id = cJSON_GetNumberValue(jid); + cJSON_AddItemToObject(jres, "id", cJSON_CreateNumber(id)); + } + if (cJSON_IsString(jmethod)) { + // router + char* method = cJSON_GetStringValue(jmethod); + bool found = false; + for (int i = 0; i < JSONRPC_ROUTER_NUM; ++i) { + if (strcmp(method, router[i].method) == 0) { + found = true; + router[i].handler(jreq, jres); + break; + } + } + if (!found) { + not_found(jreq, jres); + } + } else { + bad_request(jreq, jres); + } + + char* resp_str = cJSON_PrintUnformatted(jres); + printf("< %s\n", resp_str); + // NOTE: +1 for \0 + hio_write(io, resp_str, strlen(resp_str) + 1); + + cJSON_Delete(jreq); + cJSON_Delete(jres); + cJSON_free(resp_str); +} + +static void on_accept(hio_t* io) { + printf("on_accept connfd=%d\n", hio_fd(io)); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_set_unpack(io, &jsonrpc_unpack_setting); + hio_read(io); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + // init jsonrpc_unpack_setting + memset(&jsonrpc_unpack_setting, 0, sizeof(unpack_setting_t)); + jsonrpc_unpack_setting.mode = UNPACK_BY_DELIMITER; + jsonrpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + jsonrpc_unpack_setting.delimiter[0] = '\0'; + jsonrpc_unpack_setting.delimiter_bytes = 1; + + hloop_t* loop = hloop_new(0); + hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); + if (listenio == NULL) { + return -20; + } + printf("listenfd=%d\n", hio_fd(listenio)); + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/jsonrpc/router.h b/external/libhv/libhv-1.3.2/examples/jsonrpc/router.h new file mode 100644 index 0000000..1932747 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/jsonrpc/router.h @@ -0,0 +1,22 @@ +#ifndef HV_JSON_RPC_ROUTER_H_ +#define HV_JSON_RPC_ROUTER_H_ + +#include "cJSON.h" + +typedef void (*jsonrpc_handler)(cJSON* jreq, cJSON* jres); + +typedef struct { + const char* method; + jsonrpc_handler handler; +} jsonrpc_router; + +void error_response(cJSON* jres, int code, const char* message); +void not_found(cJSON* jreq, cJSON* jres); +void bad_request(cJSON* jreq, cJSON* jres); + +void calc_add(cJSON* jreq, cJSON* jres); +void calc_sub(cJSON* jreq, cJSON* jres); +void calc_mul(cJSON* jreq, cJSON* jres); +void calc_div(cJSON* jreq, cJSON* jres); + +#endif // HV_JSON_RPC_ROUTER_H_ diff --git a/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_client_test.cpp b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_client_test.cpp new file mode 100644 index 0000000..5fc606d --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_client_test.cpp @@ -0,0 +1,85 @@ +/* + * mqtt client + * + * @build make examples + * + * @test bin/mqtt_client_test 127.0.0.1 1883 topic payload + * + */ + +#include "mqtt_client.h" +using namespace hv; + +/* + * @test MQTTS + * #define TEST_SSL 1 + * + * @build ./configure --with-mqtt --with-openssl && make clean && make + * + */ +#define TEST_SSL 0 +#define TEST_AUTH 0 +#define TEST_RECONNECT 1 +#define TEST_QOS 0 + +int main(int argc, char** argv) { + if (argc < 5) { + printf("Usage: %s host port topic payload\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + const char* topic = argv[3]; + const char* payload = argv[4]; + + MqttClient cli; + + cli.onConnect = [topic, payload](MqttClient* cli) { + printf("connected!\n"); +#if TEST_QOS + cli->subscribe(topic, 1, [topic, payload](MqttClient* cli) { + printf("subscribe OK!\n"); + cli->publish(topic, payload, 1, 0, [](MqttClient* cli) { + printf("publish OK!\n"); + }); + }); +#else + cli->subscribe(topic); + cli->publish(topic, payload); +#endif + }; + + cli.onMessage = [](MqttClient* cli, mqtt_message_t* msg) { + printf("topic: %.*s\n", msg->topic_len, msg->topic); + printf("payload: %.*s\n", msg->payload_len, msg->payload); + cli->disconnect(); + cli->stop(); + }; + + cli.onClose = [](MqttClient* cli) { + printf("disconnected!\n"); + }; + +#if TEST_AUTH + cli.setAuth("test", "123456"); +#endif + +#if TEST_RECONNECT + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + cli.setReconnect(&reconn); +#endif + + cli.setPingInterval(10); + + int ssl = 0; +#if TEST_SSL + ssl = 1; +#endif + cli.connect(host, port, ssl); + cli.run(); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_pub.c b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_pub.c new file mode 100644 index 0000000..21b014c --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_pub.c @@ -0,0 +1,134 @@ +/* + * mqtt publish + * + * @build make examples + * @sub bin/mqtt_sub 127.0.0.1 1883 topic + * @pub bin/mqtt_pub 127.0.0.1 1883 topic payload + * + */ + +#include "hv.h" +#include "mqtt_client.h" + +/* + * @test MQTTS + * #define TEST_SSL 1 + * + * @build ./configure --with-mqtt --with-openssl && make clean && make + * + */ +#define TEST_SSL 0 +#define TEST_AUTH 0 + +/* + * workflow: + * mqtt_client_new -> mqtt_client_xxx -> mqtt_client_run + * + * mqtt_client_set_xxx -> + * mqtt_client_connect -> + * on_connack -> mqtt_client_publish -> + * on_puback -> mqtt_client_disconnect -> + * on_disconnect -> mqtt_client_stop + * + */ + +static void on_mqtt(mqtt_client_t* cli, int type) { + printf("on_mqtt type=%d\n", type); + switch(type) { + case MQTT_TYPE_CONNECT: + printf("mqtt connected!\n"); + break; + case MQTT_TYPE_DISCONNECT: + printf("mqtt disconnected!\n"); + { + mqtt_message_t* msg = (mqtt_message_t*)mqtt_client_get_userdata(cli); + HV_FREE(msg); + mqtt_client_set_userdata(cli, NULL); + mqtt_client_stop(cli); + } + break; + case MQTT_TYPE_CONNACK: + printf("mqtt connack!\n"); + { + mqtt_message_t* msg = (mqtt_message_t*)mqtt_client_get_userdata(cli); + if (msg == NULL) return; + int mid = mqtt_client_publish(cli, msg); + printf("mqtt publish mid=%d\n", mid); + if (msg->qos == 0) { + mqtt_client_disconnect(cli); + } else if (msg->qos == 1) { + // wait MQTT_TYPE_PUBACK + } else if (msg->qos == 2) { + // wait MQTT_TYPE_PUBREC + } + } + break; + case MQTT_TYPE_PUBACK: /* qos = 1 */ + printf("mqtt puback mid=%d\n", cli->mid); + mqtt_client_disconnect(cli); + break; + case MQTT_TYPE_PUBREC: /* qos = 2 */ + printf("mqtt pubrec mid=%d\n", cli->mid); + // wait MQTT_TYPE_PUBCOMP + break; + case MQTT_TYPE_PUBCOMP: /* qos = 2 */ + printf("mqtt pubcomp mid=%d\n", cli->mid); + mqtt_client_disconnect(cli); + break; + default: + break; + } +} + +static int mqtt_publish(const char* host, int port, const char* topic, const char* payload) { + mqtt_client_t* cli = mqtt_client_new(NULL); + if (cli == NULL) return -1; + cli->keepalive = 10; + + // client_id + char client_id[64]; + snprintf(client_id, sizeof(client_id), "mqtt_pub_%ld", hv_getpid()); + printf("client_id: %s\n", client_id); + mqtt_client_set_id(cli, client_id); + // will + mqtt_message_t will; + memset(&will, 0, sizeof(will)); + will.topic = "will"; + will.payload = "This is a will."; + mqtt_client_set_will(cli, &will); +#if TEST_AUTH + mqtt_client_set_auth(cli, "test", "123456"); +#endif + + mqtt_message_t* msg = NULL; + HV_ALLOC_SIZEOF(msg); + msg->topic = topic; + msg->topic_len = strlen(topic); + msg->payload = payload; + msg->payload_len = strlen(payload); + msg->qos = 1; + mqtt_client_set_userdata(cli, msg); + mqtt_client_set_callback(cli, on_mqtt); + + int ssl = 0; +#if TEST_SSL + ssl = 1; +#endif + mqtt_client_connect(cli, host, port, ssl); + mqtt_client_run(cli); + mqtt_client_free(cli); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 5) { + printf("Usage: %s host port topic payload\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + const char* topic = argv[3]; + const char* payload = argv[4]; + + return mqtt_publish(host, port, topic, payload); +} diff --git a/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_sub.c b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_sub.c new file mode 100644 index 0000000..1eb8e2d --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/mqtt/mqtt_sub.c @@ -0,0 +1,114 @@ +/* + * mqtt subscribe + * + * @build make examples + * @sub bin/mqtt_sub 127.0.0.1 1883 topic + * @pub bin/mqtt_pub 127.0.0.1 1883 topic payload + * + */ + +#include "hv.h" +#include "mqtt_client.h" + +/* + * @test MQTTS + * #define TEST_SSL 1 + * + * @build ./configure --with-mqtt --with-openssl && make clean && make + * + */ +#define TEST_SSL 0 +#define TEST_AUTH 0 +#define TEST_RECONNECT 1 + +/* + * workflow: + * mqtt_client_new -> mqtt_client_xxx -> mqtt_client_run + * + * mqtt_client_set_xxx -> + * mqtt_client_connect -> + * on_connack -> mqtt_client_subscribe -> + * on_publish -> handle_message + * + */ + +static void handle_message(mqtt_client_t* cli, mqtt_message_t* msg) { + printf("topic: %.*s\n", msg->topic_len, msg->topic); + printf("payload: %.*s\n", msg->payload_len, msg->payload); +} + +static void on_mqtt(mqtt_client_t* cli, int type) { + printf("on_mqtt type=%d\n", type); + switch(type) { + case MQTT_TYPE_CONNECT: + printf("mqtt connected!\n"); + if (cli->reconn_setting && cli->reconn_setting->cur_retry_cnt > 0) { + printf("mqtt reconnect cnt=%d, delay=%d\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); + } + break; + case MQTT_TYPE_DISCONNECT: + printf("mqtt disconnected!\n"); + if (cli->reconn_setting && cli->reconn_setting->cur_retry_cnt > 0) { + printf("mqtt reconnect cnt=%d, delay=%d\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); + } + break; + case MQTT_TYPE_CONNACK: + printf("mqtt connack!\n"); + { + const char* topic = (const char*)mqtt_client_get_userdata(cli); + int mid = mqtt_client_subscribe(cli, topic, 0); + printf("mqtt subscribe mid=%d\n", mid); + } + break; + case MQTT_TYPE_SUBACK: + printf("mqtt suback mid=%d\n", cli->mid); + break; + case MQTT_TYPE_PUBLISH: + handle_message(cli, &cli->message); + default: + break; + } +} + +static int mqtt_subscribe(const char* host, int port, const char* topic) { + mqtt_client_t* cli = mqtt_client_new(NULL); + if (cli == NULL) return -1; + cli->keepalive = 10; + +#if TEST_AUTH + mqtt_client_set_auth(cli, "test", "123456"); +#endif + + mqtt_client_set_userdata(cli, (void*)topic); + mqtt_client_set_callback(cli, on_mqtt); + +#if TEST_RECONNECT + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + mqtt_client_set_reconnect(cli, &reconn); +#endif + + int ssl = 0; +#if TEST_SSL + ssl = 1; +#endif + mqtt_client_connect(cli, host, port, ssl); + mqtt_client_run(cli); + mqtt_client_free(cli); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 4) { + printf("Usage: %s host port topic\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + const char* topic = argv[3]; + + return mqtt_subscribe(host, port, topic); +} diff --git a/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-processes.c b/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-processes.c new file mode 100644 index 0000000..edfce30 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-processes.c @@ -0,0 +1,98 @@ +/* + * + * @build make examples + * @server bin/multi-acceptor-processes 1234 + * @client bin/nc 127.0.0.1 1234 + * nc 127.0.0.1 1234 + * telnet 127.0.0.1 1234 + */ + +#include "hloop.h" +#include "hsocket.h" +#include "hthread.h" +#include "hproc.h" + +static char protocol = 't'; +static const char* protocolname = "tcp"; +static const char* host = "0.0.0.0"; +static int port = 1234; +static int process_num = 4; + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + // echo + hio_write(io, buf, readbytes); +} + +static void on_accept(hio_t* io) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("pid=%ld connfd=%d [%s] <= [%s]\n", + (long)hv_getpid(), + (int)hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_read(io); +} + +static void loop_proc(void* userdata) { + int sockfd = (int)(intptr_t)(userdata); + hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + hio_t* io = hio_get(loop, sockfd); + if (protocol == 't') { + hio_setcb_accept(io, on_accept); + hio_accept(io); + } + else if (protocol == 'u') { + hio_setcb_read(io, on_recv); + hio_read(io); + } + hloop_run(loop); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + int index = 1; + if (argv[1][0] == '-') { + protocol = argv[1][1]; + switch(protocol) { + case 't': protocolname = "tcp"; break; + case 'u': protocolname = "udp"; break; + default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); + } + ++index; + } + port = atoi(argv[index++]); + + int sockfd = -1; + if (protocol == 't') { + sockfd = Listen(port, host); + } + else if (protocol == 'u') { + sockfd = Bind(port, host, SOCK_DGRAM); + } + if (sockfd < 0) { + exit(1); + } + + proc_ctx_t ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.proc = loop_proc; + ctx.proc_userdata = (void*)(intptr_t)sockfd; + for (int i = 0; i < process_num; ++i) { + hproc_spawn(&ctx); + } + + while(1) hv_sleep(1); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-threads.c b/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-threads.c new file mode 100644 index 0000000..cd101d9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/multi-thread/multi-acceptor-threads.c @@ -0,0 +1,94 @@ +/* + * + * @build make examples + * @server bin/multi-acceptor-threads 1234 + * @client bin/nc 127.0.0.1 1234 + * nc 127.0.0.1 1234 + * telnet 127.0.0.1 1234 + */ + +#include "hloop.h" +#include "hsocket.h" +#include "hthread.h" + +static char protocol = 't'; +static const char* protocolname = "tcp"; +static const char* host = "0.0.0.0"; +static int port = 1234; +static int thread_num = 4; + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + // echo + hio_write(io, buf, readbytes); +} + +static void on_accept(hio_t* io) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("tid=%ld connfd=%d [%s] <= [%s]\n", + (long)hv_gettid(), + (int)hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_read(io); +} + +static HTHREAD_ROUTINE(loop_thread) { + int sockfd = (int)(intptr_t)(userdata); + hloop_t* loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + hio_t* io = hio_get(loop, sockfd); + if (protocol == 't') { + hio_setcb_accept(io, on_accept); + hio_accept(io); + } + else if (protocol == 'u') { + hio_setcb_read(io, on_recv); + hio_read(io); + } + hloop_run(loop); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd [-tu] port\n"); + return -10; + } + int index = 1; + if (argv[1][0] == '-') { + protocol = argv[1][1]; + switch(protocol) { + case 't': protocolname = "tcp"; break; + case 'u': protocolname = "udp"; break; + default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); + } + ++index; + } + port = atoi(argv[index++]); + + int sockfd = -1; + if (protocol == 't') { + sockfd = Listen(port, host); + } + else if (protocol == 'u') { + sockfd = Bind(port, host, SOCK_DGRAM); + } + if (sockfd < 0) { + exit(1); + } + + for (int i = 0; i < thread_num; ++i) { + hthread_create(loop_thread, (void*)(intptr_t)sockfd); + } + + while(1) hv_sleep(1); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/multi-thread/one-acceptor-multi-workers.c b/external/libhv/libhv-1.3.2/examples/multi-thread/one-acceptor-multi-workers.c new file mode 100644 index 0000000..4eb1946 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/multi-thread/one-acceptor-multi-workers.c @@ -0,0 +1,100 @@ +/* + * + * @build make examples + * @server bin/one-acceptor-multi-workers 1234 + * @client bin/nc 127.0.0.1 1234 + * nc 127.0.0.1 1234 + * telnet 127.0.0.1 1234 + */ + +#include "hloop.h" +#include "hsocket.h" +#include "hthread.h" + +static const char* host = "0.0.0.0"; +static int port = 1234; +static int thread_num = 4; +static hloop_t* accept_loop = NULL; +static hloop_t** worker_loops = NULL; + +static hloop_t* get_next_loop() { + static int s_cur_index = 0; + if (++s_cur_index >= thread_num) { + s_cur_index = 0; + } + return worker_loops[s_cur_index % thread_num]; +} + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + // echo + hio_write(io, buf, readbytes); +} + +static void new_conn_event(hevent_t* ev) { + hloop_t* loop = ev->loop; + hio_t* io = (hio_t*)hevent_userdata(ev); + hio_attach(loop, io); + + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("tid=%ld connfd=%d [%s] <= [%s]\n", + (long)hv_gettid(), + (int)hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_read(io); +} + +static void on_accept(hio_t* io) { + hio_detach(io); + + hloop_t* worker_loop = get_next_loop(); + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.loop = worker_loop; + ev.cb = new_conn_event; + ev.userdata = io; + hloop_post_event(worker_loop, &ev); +} + +static HTHREAD_ROUTINE(worker_thread) { + hloop_t* loop = (hloop_t*)userdata; + hloop_run(loop); + return 0; +} + +static HTHREAD_ROUTINE(accept_thread) { + hloop_t* loop = (hloop_t*)userdata; + hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); + if (listenio == NULL) { + exit(1); + } + hloop_run(loop); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: cmd port\n"); + return -10; + } + port = atoi(argv[1]); + + worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); + for (int i = 0; i < thread_num; ++i) { + worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); + hthread_create(worker_thread, worker_loops[i]); + } + + accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + accept_thread(accept_loop); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/nc.c b/external/libhv/libhv-1.3.2/examples/nc.c new file mode 100644 index 0000000..69e6e04 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/nc.c @@ -0,0 +1,240 @@ +/* + * network client + * + * @build: make examples + * @server bin/httpd -s restart -d + * @usage: bin/nc 127.0.0.1 8080 + * > GET / HTTP/1.1 + * > Connection: close + * > [Enter] + * > GET / HTTP/1.1 + * > Connection: keep-alive + * > [Enter] + */ + +/* + * @test udp client + * @build ./configure && make examples + * @client bin/nc -u 127.0.0.1 1234 + * + */ + +/* + * @test ssl client + * @build ./configure --with-openssl && make clean && make + * @client bin/nc -s 127.0.0.1 1234 + * + */ + +/* + * @test kcp client + * @build ./configure --with-kcp && make clean && make + * @client bin/nc -k 127.0.0.1 1234 + * + */ + +#include "hloop.h" +#include "hbase.h" +#include "hsocket.h" +#include "hssl.h" + +#define RECV_BUFSIZE 8192 +static char recvbuf[RECV_BUFSIZE]; + +static char protocol = 't'; +static const char* protocolname = "tcp"; +// for stdin +static hio_t* stdinio = NULL; +// for socket +static hio_t* sockio = NULL; + +static int verbose = 0; + +static void send_heartbeat(hio_t* io) { + static char buf[] = "PING\r\n"; + // printf("send_heartbeat %s", buf); + hio_write(io, buf, 6); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + printf("%.*s", readbytes, (char*)buf); + + // test hio_set_readbuf in hread_cb +#if 0 + static int total_readbytes = 0; + total_readbytes += readbytes; + if (total_readbytes >= RECV_BUFSIZE) { + total_readbytes = 0; + } + hio_set_readbuf(io, recvbuf + total_readbytes, RECV_BUFSIZE - total_readbytes); + printf("%.*s", total_readbytes, recvbuf); +#endif + + fflush(stdout); +} + +static void on_stdin(hio_t* io, void* buf, int readbytes) { + // printf("on_stdin fd=%d readbytes=%d\n", hio_fd(io), readbytes); + // printf("> %s\n", buf); + + char* str = (char*)buf; + + // test hio_read_start/hio_read_stop/hio_close/hloop_stop +#if 1 + if (strncmp(str, "start", 5) == 0) { + printf("call hio_read_start\n"); + hio_read_start(sockio); + return; + } + else if (strncmp(str, "stop", 4) == 0) { + printf("call hio_read_stop\n"); + hio_read_stop(sockio); + return; + } + else if (strncmp(str, "close", 5) == 0) { + printf("call hio_close\n"); + hio_close(sockio); + return; + } + else if (strncmp(str, "quit", 4) == 0) { + printf("call hloop_stop\n"); + hloop_stop(hevent_loop(io)); + return; + } +#endif + + // CR|LF => CRLF for test most protocols + char eol = str[readbytes-1]; + if (eol == '\n' || eol == '\r') { + if (readbytes > 1 && str[readbytes-2] == '\r' && eol == '\n') { + // have been CRLF + } + else { + ++readbytes; + str[readbytes - 2] = '\r'; + str[readbytes - 1] = '\n'; + } + } + + hio_write(sockio, buf, readbytes); + + if (strncmp(str, "CLOSE", 5) == 0) { + printf("call hio_close\n"); + hio_close(sockio); + } +} + +static void on_close(hio_t* io) { + // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + hio_del(stdinio, HV_READ); +} + +static void on_connect(hio_t* io) { + // printf("on_connect fd=%d\n", hio_fd(io)); + if (verbose) { + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("connect connfd=%d [%s] => [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + } + + hio_read_start(io); + // uncomment to test heartbeat + // hio_set_heartbeat(sockio, 3000, send_heartbeat); +} + +int main(int argc, char** argv) { + if (argc < 3) { + printf("\ +Usage: nc [-tusk] host port\n\ +Options:\n\ + -t Use tcp protocol (default)\n\ + -u Use udp protocol\n\ + -s Use ssl protocol\n\ + -k Use kcp protocol\n\ +Examples: nc 127.0.0.1 80\n\ + nc -u 127.0.0.1 80\n"); + return -10; + } + + int index = 1; + if (argv[1][0] == '-') { + protocol = argv[1][1]; + switch(protocol) { + case 't': protocolname = "tcp"; break; + case 'u': protocolname = "udp"; break; + case 's': protocolname = "ssl"; break; + case 'k': protocolname = "kcp"; break; + default: fprintf(stderr, "Unsupported protocol '%c'\n", protocol); exit(1); + } + ++index; + } + const char* host = argv[index++]; + int port = atoi(argv[index++]); + if (verbose) { + printf("%s %s %d\n", protocolname, host, port); + } + + HV_MEMCHECK; + + hloop_t* loop = hloop_new(HLOOP_FLAG_QUIT_WHEN_NO_ACTIVE_EVENTS); + + // stdin use default readbuf + stdinio = hread(loop, 0, NULL, 0, on_stdin); + if (stdinio == NULL) { + return -20; + } + + // socket + if (protocol == 't' || protocol == 's') { + // tcp + sockio = hloop_create_tcp_client(loop, host, port, on_connect, on_close); + if (sockio == NULL) { + return -20; + } + if (protocol == 's') { + if (strcmp(hssl_backend(), "nossl") == 0) { + fprintf(stderr, "Please recompile WITH_SSL!\n"); + exit(1); + } + hio_enable_ssl(sockio); + } + } + else if (protocol == 'u' || protocol == 'k') { + // udp + sockio = hloop_create_udp_client(loop, host, port); + if (sockio == NULL) { + return -20; + } + if (protocol == 'k') { +#if WITH_KCP + static kcp_setting_t s_kcp_setting; + kcp_setting_init_with_normal_mode(&s_kcp_setting); + s_kcp_setting.conv = hv_rand(1, 999999); + hio_set_kcp(sockio, &s_kcp_setting); +#else + fprintf(stderr, "Please recompile WITH_KCP!\n"); + exit(1); +#endif + } + hio_read(sockio); + } + // printf("sockfd=%d\n", hio_fd(sockio)); + hio_setcb_close(sockio, on_close); + hio_setcb_read(sockio, on_recv); + hio_set_readbuf(sockio, recvbuf, RECV_BUFSIZE); + + hloop_run(loop); + hloop_free(&loop); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/nmap/main.cpp b/external/libhv/libhv-1.3.2/examples/nmap/main.cpp new file mode 100644 index 0000000..7063630 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/nmap/main.cpp @@ -0,0 +1,115 @@ +#include +#include + +#include + +#include "nmap.h" +#include "hsocket.h" +#include "hthreadpool.h" + +int host_discover_task(std::string segment, void* nmap) { + Nmap* hosts= (Nmap*)nmap; + return host_discover(segment.c_str(), hosts); +} + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: nmap segment\n"); + printf("Examples: nmap 192.168.1.123\n"); + printf(" nmap 192.168.1.x/24\n"); + printf(" nmap 192.168.x.x/16\n"); + return -1; + } + + char* segment = argv[1]; + char* split = strchr(segment, '/'); + int n = 24; + if (split) { + *split = '\0'; + n = atoi(split+1); + if (n != 24 && n != 16) { + return -2; + } + } + + Nmap hosts; + char ip[INET_ADDRSTRLEN]; + if (n == 24) { + host_discover(segment, &hosts); + } + else if (n == 16) { + Nmap segs; + int up_nsegs = segment_discover(segment, &segs); + if (up_nsegs == 0) return 0; +#if 1 + for (auto& pair : segs) { + if (pair.second == 1) { + uint32_t addr = pair.first; + uint8_t* p = (uint8_t*)&addr; + // 0,255 reserved + for (int i = 1; i < 255; ++i) { + p[3] = i; + hosts[addr] = 0; + } + } + } + nmap_discover(&hosts); +#else + if (up_nsegs == 1) { + for (auto& pair : segs) { + if (pair.second == 1) { + inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip)); + host_discover(ip, &hosts); + } + } + } + else { + // ThreadPool + host_discover + Nmap* hosts = new Nmap[up_nsegs]; + // use ThreadPool + HThreadPool tp(4); + tp.start(); + std::vector> futures; + int i = 0; + for (auto& pair : segs) { + if (pair.second == 1) { + inet_ntop(AF_INET, (void*)&pair.first, ip, sizeof(ip)); + auto future = tp.commit(host_discover_task, std::string(ip), &hosts[i++]); + futures.push_back(std::move(future)); + } + } + // wait all task done + int nhosts = 0; + for (auto& future : futures) { + nhosts += future.get(); + } + // filter up hosts + std::vector up_hosts; + for (int i = 0; i < up_nsegs; ++i) { + Nmap& nmap = hosts[i]; + for (auto& host : nmap) { + if (host.second == 1) { + up_hosts.push_back(host.first); + } + } + } + delete[] hosts; + } +#endif + } + + // filter up hosts + std::vector up_hosts; + for (auto& pair : hosts) { + if (pair.second == 1) { + up_hosts.push_back(pair.first); + } + } + // print up hosts + printf("Up hosts %lu:\n", (unsigned long)up_hosts.size()); + for (auto& host : up_hosts) { + inet_ntop(AF_INET, (void*)&host, ip, sizeof(ip)); + printf("%s\n", ip); + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/nmap/nmap.cpp b/external/libhv/libhv-1.3.2/examples/nmap/nmap.cpp new file mode 100644 index 0000000..90a3634 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/nmap/nmap.cpp @@ -0,0 +1,177 @@ +#include "nmap.h" +#include "hloop.h" +#include "hstring.h" +#include "hsocket.h" +#include "netinet.h" + +using namespace hv; + +#define MAX_RECVFROM_TIMEOUT 5000 // ms +#define MAX_SENDTO_PERSOCKET 1024 + +typedef struct nmap_ctx_s { + Nmap* nmap; + int send_cnt; + int recv_cnt; + int up_cnt; + int idle_cnt; +} nmap_ctx_t; + +static void on_idle(hidle_t* idle) { + hloop_t* loop = hevent_loop(idle); + nmap_ctx_t* ctx = (nmap_ctx_t*)hloop_userdata(loop); + ctx->idle_cnt++; + if (ctx->idle_cnt == 1) { + // try again? + } + hloop_stop(loop); +} + +static void on_timer(htimer_t* timer) { + hloop_t* loop = hevent_loop(timer); + hloop_stop(loop); +} + +static void on_recvfrom(hio_t* io, void* buf, int readbytes) { + //printd("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printd("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + hloop_t* loop = hevent_loop(io); + nmap_ctx_t* ctx = (nmap_ctx_t*)hloop_userdata(loop); + if (++ctx->recv_cnt == ctx->send_cnt) { + //hloop_stop(loop); + } + Nmap* nmap = ctx->nmap; + struct sockaddr_in* peeraddr = (struct sockaddr_in*)hio_peeraddr(io); + auto iter = nmap->find(peeraddr->sin_addr.s_addr); + if (iter != nmap->end()) { + if (iter->second == 0) { + iter->second = 1; + if (++ctx->up_cnt == nmap->size()) { + hloop_stop(loop); + } + } + } +} + +int nmap_discover(Nmap* nmap) { + hloop_t* loop = hloop_new(0); + uint64_t start_hrtime = hloop_now_hrtime(loop); + + nmap_ctx_t ctx; + ctx.nmap = nmap; + ctx.send_cnt = 0; + ctx.recv_cnt = 0; + ctx.up_cnt = 0; + ctx.idle_cnt = 0; + hloop_set_userdata(loop, &ctx); + + char recvbuf[128]; + // icmp + char sendbuf[44]; // 20IP + 44ICMP = 64 + icmp_t* icmp_req = (icmp_t*)sendbuf; + icmp_req->icmp_type = ICMP_ECHO; + icmp_req->icmp_code = 0; + icmp_req->icmp_id = getpid(); + for (int i = 0; i < sizeof(sendbuf) - sizeof(icmphdr_t); ++i) { + icmp_req->icmp_data[i] = i; + } + struct sockaddr_in peeraddr; + hio_t* io = NULL; + for (auto iter = nmap->begin(); iter != nmap->end(); ++iter) { + if (iter->second == 1) continue; + if (ctx.send_cnt % MAX_SENDTO_PERSOCKET == 0) { + // socket + int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (sockfd < 0) { + perror("socket"); + if (errno == EPERM) { + fprintf(stderr, "please use root or sudo to create a raw socket.\n"); + } + return -socket_errno(); + } + nonblocking(sockfd); + so_sndbuf(sockfd, 425984); // 416K + + io = hio_get(loop, sockfd); + if (io == NULL) return -1; + hio_set_type(io, HIO_TYPE_IP); + struct sockaddr_in localaddr; + socklen_t addrlen = sizeof(localaddr); + memset(&localaddr, 0, addrlen); + localaddr.sin_addr.s_addr = htonl(INADDR_ANY); + hio_set_localaddr(io, (struct sockaddr*)&localaddr, addrlen); + hrecvfrom(loop, sockfd, recvbuf, sizeof(recvbuf), on_recvfrom); + } + icmp_req->icmp_seq = iter->first; + icmp_req->icmp_cksum = 0; + icmp_req->icmp_cksum = checksum((uint8_t*)icmp_req, sizeof(sendbuf)); + socklen_t addrlen = sizeof(peeraddr); + memset(&peeraddr, 0, addrlen); + peeraddr.sin_family = AF_INET; + peeraddr.sin_addr.s_addr = iter->first; + hio_set_peeraddr(io, (struct sockaddr*)&peeraddr, addrlen); + hsendto(loop, hio_fd(io), sendbuf, sizeof(sendbuf), NULL); + ++ctx.send_cnt; + } + + htimer_add(loop, on_timer, MAX_RECVFROM_TIMEOUT, 1); + hidle_add(loop, on_idle, 3); + + hloop_run(loop); + uint64_t end_hrtime = hloop_now_hrtime(loop); + hloop_free(&loop); + + // print result + char ip[INET_ADDRSTRLEN]; + auto iter = nmap->begin(); + while (iter != nmap->end()) { + inet_ntop(AF_INET, (void*)&iter->first, ip, sizeof(ip)); + printd("%s\t is %s.\n", ip, iter->second == 0 ? "down" : "up"); + ++iter; + } + printd("Nmap done: %lu IP addresses (%d hosts up) scanned in %.2f seconds\n", + (unsigned long)nmap->size(), ctx.up_cnt, (end_hrtime-start_hrtime)/1000000.0f); + + return ctx.up_cnt; +} + +int segment_discover(const char* segment16, Nmap* nmap) { + StringList strlist = split(segment16, '.'); + if (strlist.size() != 4) return -1; + uint32_t addr = 0; + uint8_t* p = (uint8_t*)&addr; + p[0] = atoi(strlist[0].c_str()); + p[1] = atoi(strlist[1].c_str()); + p[3] = 1; + printd("Nmap scan %u.%u.x.1...\n", p[0], p[1]); + nmap->clear(); + for (int i = 0; i < 256; ++i) { + p[2] = i; + (*nmap)[addr] = 0; + } + return nmap_discover(nmap); +} + +int host_discover(const char* segment24, Nmap* nmap) { + StringList strlist = split(segment24, '.'); + if (strlist.size() != 4) return -1; + uint32_t addr = 0; + uint8_t* p = (uint8_t*)&addr; + p[0] = atoi(strlist[0].c_str()); + p[1] = atoi(strlist[1].c_str()); + p[2] = atoi(strlist[2].c_str()); + printd("Nmap scan %u.%u.%u.x...\n", p[0], p[1], p[2]); + // 0,255 reserved + nmap->clear(); + for (int i = 1; i < 255; ++i) { + p[3] = i; + (*nmap)[addr] = 0; + } + return nmap_discover(nmap); +} diff --git a/external/libhv/libhv-1.3.2/examples/nmap/nmap.h b/external/libhv/libhv-1.3.2/examples/nmap/nmap.h new file mode 100644 index 0000000..3975c2d --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/nmap/nmap.h @@ -0,0 +1,19 @@ +#ifndef HV_NMAP_H_ +#define HV_NMAP_H_ + +#include +#include + +// addr => 0:down 1:up +typedef std::map Nmap; + +// ip = segment + host +// segment16: 192.168.x.x +// segment24: 192.168.1.x + +// @return up_cnt +int nmap_discover(Nmap* nmap); +int segment_discover(const char* segment16, Nmap* nmap); +int host_discover(const char* segment24, Nmap* nmap); + +#endif // HV_NMAP_H_ diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/handler/calc.h b/external/libhv/libhv-1.3.2/examples/protorpc/handler/calc.h new file mode 100644 index 0000000..d727eaf --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/handler/calc.h @@ -0,0 +1,79 @@ +#ifndef HV_PROTO_RPC_HANDLER_CALC_H_ +#define HV_PROTO_RPC_HANDLER_CALC_H_ + +#include "../router.h" + +#include "../generated/calc.pb.h" + +void calc_add(const protorpc::Request& req, protorpc::Response* res) { + // params + if (req.params_size() != 2) { + return bad_request(req, res); + } + protorpc::CalcParam param1, param2; + if (!param1.ParseFromString(req.params(0)) || + !param2.ParseFromString(req.params(1))) { + return bad_request(req, res); + } + + // result + protorpc::CalcResult result; + result.set_num(param1.num() + param2.num()); + res->set_result(result.SerializeAsString()); +} + +void calc_sub(const protorpc::Request& req, protorpc::Response* res) { + // params + if (req.params_size() != 2) { + return bad_request(req, res); + } + protorpc::CalcParam param1, param2; + if (!param1.ParseFromString(req.params(0)) || + !param2.ParseFromString(req.params(1))) { + return bad_request(req, res); + } + + // result + protorpc::CalcResult result; + result.set_num(param1.num() - param2.num()); + res->set_result(result.SerializeAsString()); +} + +void calc_mul(const protorpc::Request& req, protorpc::Response* res) { + // params + if (req.params_size() != 2) { + return bad_request(req, res); + } + protorpc::CalcParam param1, param2; + if (!param1.ParseFromString(req.params(0)) || + !param2.ParseFromString(req.params(1))) { + return bad_request(req, res); + } + + // result + protorpc::CalcResult result; + result.set_num(param1.num() * param2.num()); + res->set_result(result.SerializeAsString()); +} + +void calc_div(const protorpc::Request& req, protorpc::Response* res) { + // params + if (req.params_size() != 2) { + return bad_request(req, res); + } + protorpc::CalcParam param1, param2; + if (!param1.ParseFromString(req.params(0)) || + !param2.ParseFromString(req.params(1))) { + return bad_request(req, res); + } + if (param2.num() == 0) { + return bad_request(req, res); + } + + // result + protorpc::CalcResult result; + result.set_num(param1.num() / param2.num()); + res->set_result(result.SerializeAsString()); +} + +#endif // HV_PROTO_RPC_HANDLER_CALC_H_ diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/handler/handler.h b/external/libhv/libhv-1.3.2/examples/protorpc/handler/handler.h new file mode 100644 index 0000000..87c2a95 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/handler/handler.h @@ -0,0 +1,19 @@ +#ifndef HV_PROTO_RPC_HANDLER_H_ +#define HV_PROTO_RPC_HANDLER_H_ + +#include "../router.h" + +void error_response(protorpc::Response* res, int code, const std::string& message) { + res->mutable_error()->set_code(code); + res->mutable_error()->set_message(message); +} + +void not_found(const protorpc::Request& req, protorpc::Response* res) { + error_response(res, 404, "Not Found"); +} + +void bad_request(const protorpc::Request& req, protorpc::Response* res) { + error_response(res, 400, "Bad Request"); +} + +#endif // HV_PROTO_RPC_HANDLER_H_ diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/handler/login.h b/external/libhv/libhv-1.3.2/examples/protorpc/handler/login.h new file mode 100644 index 0000000..9cd5f79 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/handler/login.h @@ -0,0 +1,25 @@ +#ifndef HV_PROTO_RPC_HANDLER_LOGIN_H_ +#define HV_PROTO_RPC_HANDLER_LOGIN_H_ + +#include "../router.h" + +#include "../generated/login.pb.h" + +void login(const protorpc::Request& req, protorpc::Response* res) { + // params + if (req.params_size() == 0) { + return bad_request(req, res); + } + protorpc::LoginParam param; + if (!param.ParseFromString(req.params(0))) { + return bad_request(req, res); + } + + // result + protorpc::LoginResult result; + result.set_user_id(123456); + result.set_token(param.username() + ":" + param.password()); + res->set_result(result.SerializeAsString()); +} + +#endif // HV_PROTO_RPC_HANDLER_LOGIN_H_ diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/proto/base.proto b/external/libhv/libhv-1.3.2/examples/protorpc/proto/base.proto new file mode 100644 index 0000000..bebaec5 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/proto/base.proto @@ -0,0 +1,20 @@ +syntax = "proto3"; + +package protorpc; + +message Error { + int32 code = 1; + string message = 2; +} + +message Request { + uint64 id = 1; + string method = 2; + repeated bytes params = 3; +} + +message Response { + uint64 id = 1; + bytes result = 2; + Error error = 3; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/proto/calc.proto b/external/libhv/libhv-1.3.2/examples/protorpc/proto/calc.proto new file mode 100644 index 0000000..2ad16ec --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/proto/calc.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +package protorpc; + +message CalcParam { + int64 num = 1; +} + +message CalcResult { + int64 num = 1; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/proto/login.proto b/external/libhv/libhv-1.3.2/examples/protorpc/proto/login.proto new file mode 100644 index 0000000..6897bc6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/proto/login.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; + +package protorpc; + +message LoginParam { + string username = 1; + string password = 2; +} + +message LoginResult { + uint64 user_id = 1; + string token = 2; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/proto/protoc.sh b/external/libhv/libhv-1.3.2/examples/protorpc/proto/protoc.sh new file mode 100755 index 0000000..7e68c48 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/proto/protoc.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +cd `dirname $0` + +PROTOC=`which protoc` +if [ $? -ne 0 ]; then + echo "Not found command protoc!" + echo "Please install libprotobuf first!" + exit 1 +fi + +CPP_OUT_DIR=../generated +if [ ! -d "${CPP_OUT_DIR}" ]; then + mkdir -p ${CPP_OUT_DIR} +fi + +set -x +${PROTOC} --cpp_out=${CPP_OUT_DIR} *.proto diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.c b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.c new file mode 100644 index 0000000..1e3dbd8 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.c @@ -0,0 +1,65 @@ +#include "protorpc.h" + +#include // import memcpy + +int protorpc_pack(const protorpc_message* msg, void* buf, int len) { + if (!msg || !buf || !len) return -1; + const protorpc_head* head = &(msg->head); + unsigned int packlen = protorpc_package_length(head); + // Check is buffer enough + if (len < packlen) { + return -2; + } + unsigned char* p = (unsigned char*)buf; + *p++ = head->protocol[0]; + *p++ = head->protocol[1]; + *p++ = head->protocol[2]; + *p++ = head->protocol[3]; + *p++ = head->version; + *p++ = head->flags; + *p++ = head->reserved[0]; + *p++ = head->reserved[1]; + // hton length + unsigned int length = head->length; + *p++ = (length >> 24) & 0xFF; + *p++ = (length >> 16) & 0xFF; + *p++ = (length >> 8) & 0xFF; + *p++ = length & 0xFF; + // memcpy body + if (msg->body && head->length) { + memcpy(p, msg->body, head->length); + } + + return packlen; +} + +int protorpc_unpack(protorpc_message* msg, const void* buf, int len) { + if (!msg || !buf || !len) return -1; + if (len < PROTORPC_HEAD_LENGTH) return -2; + protorpc_head* head = &(msg->head); + const unsigned char* p = (const unsigned char*)buf; + head->protocol[0] = *p++; + head->protocol[1] = *p++; + head->protocol[2] = *p++; + head->protocol[3] = *p++; + head->version = *p++; + head->flags = *p++; + head->reserved[0] = *p++; + head->reserved[1] = *p++; + // ntoh length + head->length = ((unsigned int)*p++) << 24; + head->length |= ((unsigned int)*p++) << 16; + head->length |= ((unsigned int)*p++) << 8; + head->length |= *p++; + // Check is buffer enough + unsigned int packlen = protorpc_package_length(head); + if (len < packlen) { + return -3; + } + // NOTE: just shadow copy + if (len > PROTORPC_HEAD_LENGTH) { + msg->body = (const char*)buf + PROTORPC_HEAD_LENGTH; + } + + return packlen; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.h b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.h new file mode 100644 index 0000000..e1ef921 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc.h @@ -0,0 +1,68 @@ +#ifndef HV_PROTO_RPC_H_ +#define HV_PROTO_RPC_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define PROTORPC_NAME "HRPC" +#define PROTORPC_VERSION 1 + +// protocol:4bytes + version:1byte + flags:1byte + reserved:2bytes + length:4bytes = 12bytes +#define PROTORPC_HEAD_LENGTH 12 +#define PROTORPC_HEAD_LENGTH_FIELD_OFFSET 8 +#define PROTORPC_HEAD_LENGTH_FIELD_BYTES 4 +typedef struct { + unsigned char protocol[4]; + unsigned char version; + unsigned char flags; + unsigned char reserved[2]; + unsigned int length; +} protorpc_head; + +typedef const char* protorpc_body; + +typedef struct { + protorpc_head head; + protorpc_body body; +} protorpc_message; + +static inline unsigned int protorpc_package_length(const protorpc_head* head) { + return PROTORPC_HEAD_LENGTH + head->length; +} + +static inline void protorpc_head_init(protorpc_head* head) { + // protocol = HRPC + memcpy(head->protocol, PROTORPC_NAME, 4); + head->version = PROTORPC_VERSION; + head->reserved[0] = head->reserved[1] = 0; + head->length = 0; +} + +static inline void protorpc_message_init(protorpc_message* msg) { + protorpc_head_init(&msg->head); + msg->body = NULL; +} + +static inline int protorpc_head_check(protorpc_head* head) { + if (memcmp(head->protocol, PROTORPC_NAME, 4) != 0) { + return -1; + } + if (head->version != PROTORPC_VERSION) { + return -2; + } + return 0; +} + +// @retval >0 package_length, <0 error +int protorpc_pack(const protorpc_message* msg, void* buf, int len); +// @retval >0 package_length, <0 error +int protorpc_unpack(protorpc_message* msg, const void* buf, int len); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // HV_PROTO_RPC_H_ diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_client.cpp b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_client.cpp new file mode 100644 index 0000000..2734aca --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_client.cpp @@ -0,0 +1,277 @@ +/* + * proto rpc client + * + * @build make protorpc + * @server bin/protorpc_server 1234 + * @client bin/protorpc_client 127.0.0.1 1234 add 1 2 + * + */ + +#include "TcpClient.h" + +#include +#include + +using namespace hv; + +#include "protorpc.h" +#include "generated/base.pb.h" +#include "generated/calc.pb.h" +#include "generated/login.pb.h" + +// valgrind --leak-check=full --show-leak-kinds=all +class ProtobufRAII { +public: + ProtobufRAII() { + } + ~ProtobufRAII() { + google::protobuf::ShutdownProtobufLibrary(); + } +}; +static ProtobufRAII s_protobuf; + +namespace protorpc { +typedef std::shared_ptr RequestPtr; +typedef std::shared_ptr ResponsePtr; + +enum ProtoRpcResult { + kRpcSuccess = 0, + kRpcTimeout = -1, + kRpcError = -2, + kRpcNoResult = -3, + kRpcParseError = -4, +}; + +class ProtoRpcContext { +public: + protorpc::RequestPtr req; + protorpc::ResponsePtr res; +private: + std::mutex _mutex; + std::condition_variable _cond; + +public: + void wait(int timeout_ms) { + std::unique_lock locker(_mutex); + _cond.wait_for(locker, std::chrono::milliseconds(timeout_ms)); + } + + void notify() { + _cond.notify_one(); + } +}; +typedef std::shared_ptr ContextPtr; + +class ProtoRpcClient : public TcpClient { +public: + ProtoRpcClient() : TcpClient() + { + connect_state = kInitialized; + + setConnectTimeout(5000); + + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + setReconnect(&reconn); + + // init protorpc_unpack_setting + unpack_setting_t protorpc_unpack_setting; + memset(&protorpc_unpack_setting, 0, sizeof(unpack_setting_t)); + protorpc_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; + protorpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + protorpc_unpack_setting.body_offset = PROTORPC_HEAD_LENGTH; + protorpc_unpack_setting.length_field_offset = PROTORPC_HEAD_LENGTH_FIELD_OFFSET; + protorpc_unpack_setting.length_field_bytes = PROTORPC_HEAD_LENGTH_FIELD_BYTES; + protorpc_unpack_setting.length_field_coding = ENCODE_BY_BIG_ENDIAN; + setUnpack(&protorpc_unpack_setting); + + onConnection = [this](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + connect_state = kConnected; + printf("connected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + connect_state = kDisconnectd; + printf("disconnected to %s! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + + onMessage = [this](const SocketChannelPtr& channel, Buffer* buf) { + // protorpc_unpack + protorpc_message msg; + memset(&msg, 0, sizeof(msg)); + int packlen = protorpc_unpack(&msg, buf->data(), buf->size()); + if (packlen < 0) { + printf("protorpc_unpack failed!\n"); + return; + } + assert(packlen == buf->size()); + if (protorpc_head_check(&msg.head) != 0) { + printf("protorpc_head_check failed!\n"); + return; + } + // Response::ParseFromArray + auto res = std::make_shared(); + if (!res->ParseFromArray(msg.body, msg.head.length)) { + return; + } + // id => res + calls_mutex.lock(); + auto iter = calls.find(res->id()); + if (iter == calls.end()) { + return; + } + auto ctx = iter->second; + calls_mutex.unlock(); + ctx->res = res; + ctx->notify(); + }; + } + + int connect(int port, const char* host = "127.0.0.1") { + createsocket(port, host); + connect_state = kConnecting; + start(); + return 0; + } + + protorpc::ResponsePtr call(protorpc::RequestPtr& req, int timeout_ms = 10000) { + if (connect_state != kConnected) { + return NULL; + } + static std::atomic s_id = ATOMIC_VAR_INIT(0); + req->set_id(++s_id); + req->id(); + auto ctx = std::make_shared(); + ctx->req = req; + calls[req->id()] = ctx; + // Request::SerializeToArray + protorpc_pack + protorpc_message msg; + protorpc_message_init(&msg); + msg.head.length = req->ByteSize(); + int packlen = protorpc_package_length(&msg.head); + unsigned char* writebuf = NULL; + HV_STACK_ALLOC(writebuf, packlen); + packlen = protorpc_pack(&msg, writebuf, packlen); + if (packlen > 0) { + printf("%s\n", req->DebugString().c_str()); + req->SerializeToArray(writebuf + PROTORPC_HEAD_LENGTH, msg.head.length); + channel->write(writebuf, packlen); + } + HV_STACK_FREE(writebuf); + // wait until response come or timeout + ctx->wait(timeout_ms); + auto res = ctx->res; + calls_mutex.lock(); + calls.erase(req->id()); + calls_mutex.unlock(); + if (res == NULL) { + printf("RPC timeout!\n"); + } else if (res->has_error()) { + printf("RPC error:\n%s\n", res->error().DebugString().c_str()); + } + return res; + } + + int calc(const char* method, int num1, int num2, int& out) { + auto req = std::make_shared(); + // method + req->set_method(method); + // params + protorpc::CalcParam param1, param2; + param1.set_num(num1); + param2.set_num(num2); + req->add_params()->assign(param1.SerializeAsString()); + req->add_params()->assign(param2.SerializeAsString()); + + auto res = call(req); + + if (res == NULL) return kRpcTimeout; + if (res->has_error()) return kRpcError; + if (res->result().empty()) return kRpcNoResult; + protorpc::CalcResult result; + if (!result.ParseFromString(res->result())) return kRpcParseError; + out = result.num(); + return kRpcSuccess; + } + + int login(const protorpc::LoginParam& param, protorpc::LoginResult* result) { + auto req = std::make_shared(); + // method + req->set_method("login"); + // params + req->add_params()->assign(param.SerializeAsString()); + + auto res = call(req); + + if (res == NULL) return kRpcTimeout; + if (res->has_error()) return kRpcError; + if (res->result().empty()) return kRpcNoResult; + if (!result->ParseFromString(res->result())) return kRpcParseError; + return kRpcSuccess; + } + + enum { + kInitialized, + kConnecting, + kConnected, + kDisconnectd, + } connect_state; + std::map calls; + std::mutex calls_mutex; +}; +} + +int main(int argc, char** argv) { + if (argc < 6) { + printf("Usage: %s host port method param1 param2\n", argv[0]); + printf("method = [add, sub, mul, div]\n"); + printf("Examples:\n"); + printf(" %s 127.0.0.1 1234 add 1 2\n", argv[0]); + printf(" %s 127.0.0.1 1234 div 1 0\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + const char* method = argv[3]; + const char* param1 = argv[4]; + const char* param2 = argv[5]; + + protorpc::ProtoRpcClient cli; + cli.connect(port, host); + while (cli.connect_state == protorpc::ProtoRpcClient::kConnecting) hv_msleep(1); + if (cli.connect_state == protorpc::ProtoRpcClient::kDisconnectd) { + return -20; + } + + // test login + { + protorpc::LoginParam param; + param.set_username("admin"); + param.set_password("123456"); + protorpc::LoginResult result; + if (cli.login(param, &result) == protorpc::kRpcSuccess) { + printf("login success!\n"); + printf("%s\n", result.DebugString().c_str()); + } else { + printf("login failed!\n"); + } + } + + // test calc + { + int num1 = atoi(param1); + int num2 = atoi(param2); + int result = 0; + if (cli.calc(method, num1, num2, result) == protorpc::kRpcSuccess) { + printf("calc success!\n"); + printf("%d %s %d = %d\n", num1, method, num2, result); + } else { + printf("calc failed!\n"); + } + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_server.cpp b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_server.cpp new file mode 100644 index 0000000..f50da3f --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/protorpc_server.cpp @@ -0,0 +1,141 @@ +/* + * proto rpc server + * + * @build make protorpc + * @server bin/protorpc_server 1234 + * @client bin/protorpc_client 127.0.0.1 1234 add 1 2 + * + */ + +#include "TcpServer.h" + +using namespace hv; + +#include "protorpc.h" +#include "router.h" +#include "handler/handler.h" +#include "handler/calc.h" +#include "handler/login.h" + +// valgrind --leak-check=full --show-leak-kinds=all +class ProtobufRAII { +public: + ProtobufRAII() { + } + ~ProtobufRAII() { + google::protobuf::ShutdownProtobufLibrary(); + } +}; +static ProtobufRAII s_protobuf; + +protorpc_router router[] = { + {"add", calc_add}, + {"sub", calc_sub}, + {"mul", calc_mul}, + {"div", calc_div}, + {"login", login}, +}; +#define PROTORPC_ROUTER_NUM (sizeof(router)/sizeof(router[0])) + +class ProtoRpcServer : public TcpServer { +public: + ProtoRpcServer() : TcpServer() + { + onConnection = [](const SocketChannelPtr& channel) { + std::string peeraddr = channel->peeraddr(); + if (channel->isConnected()) { + printf("%s connected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } else { + printf("%s disconnected! connfd=%d\n", peeraddr.c_str(), channel->fd()); + } + }; + onMessage = handleMessage; + // init protorpc_unpack_setting + unpack_setting_t protorpc_unpack_setting; + memset(&protorpc_unpack_setting, 0, sizeof(unpack_setting_t)); + protorpc_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; + protorpc_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + protorpc_unpack_setting.body_offset = PROTORPC_HEAD_LENGTH; + protorpc_unpack_setting.length_field_offset = PROTORPC_HEAD_LENGTH_FIELD_OFFSET; + protorpc_unpack_setting.length_field_bytes = PROTORPC_HEAD_LENGTH_FIELD_BYTES; + protorpc_unpack_setting.length_field_coding = ENCODE_BY_BIG_ENDIAN; + setUnpack(&protorpc_unpack_setting); + } + + int listen(int port) { return createsocket(port); } + +private: + static void handleMessage(const SocketChannelPtr& channel, Buffer* buf) { + // unpack -> Request::ParseFromArray -> router -> Response::SerializeToArray -> pack -> Channel::write + // protorpc_unpack + protorpc_message msg; + memset(&msg, 0, sizeof(msg)); + int packlen = protorpc_unpack(&msg, buf->data(), buf->size()); + if (packlen < 0) { + printf("protorpc_unpack failed!\n"); + return; + } + assert(packlen == buf->size()); + if (protorpc_head_check(&msg.head) != 0) { + printf("protorpc_head_check failed!\n"); + return; + } + + // Request::ParseFromArray + protorpc::Request req; + protorpc::Response res; + if (req.ParseFromArray(msg.body, msg.head.length)) { + printf("> %s\n", req.DebugString().c_str()); + res.set_id(req.id()); + // router + const char* method = req.method().c_str(); + bool found = false; + for (int i = 0; i < PROTORPC_ROUTER_NUM; ++i) { + if (strcmp(method, router[i].method) == 0) { + found = true; + router[i].handler(req, &res); + break; + } + } + if (!found) { + not_found(req, &res); + } + } else { + bad_request(req, &res); + } + + // Response::SerializeToArray + protorpc_pack + protorpc_message_init(&msg); + msg.head.length = res.ByteSize(); + packlen = protorpc_package_length(&msg.head); + unsigned char* writebuf = NULL; + HV_STACK_ALLOC(writebuf, packlen); + packlen = protorpc_pack(&msg, writebuf, packlen); + if (packlen > 0) { + printf("< %s\n", res.DebugString().c_str()); + res.SerializeToArray(writebuf + PROTORPC_HEAD_LENGTH, msg.head.length); + channel->write(writebuf, packlen); + } + HV_STACK_FREE(writebuf); + } +}; + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + ProtoRpcServer srv; + int listenfd = srv.listen(port); + if (listenfd < 0) { + return -20; + } + printf("protorpc_server listen on port %d, listenfd=%d ...\n", port, listenfd); + srv.setThreadNum(4); + srv.start(); + + while (1) hv_sleep(1); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/protorpc/router.h b/external/libhv/libhv-1.3.2/examples/protorpc/router.h new file mode 100644 index 0000000..70bae91 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/protorpc/router.h @@ -0,0 +1,24 @@ +#ifndef HV_PROTO_RPC_ROUTER_H_ +#define HV_PROTO_RPC_ROUTER_H_ + +#include "generated/base.pb.h" + +typedef void (*protorpc_handler)(const protorpc::Request& req, protorpc::Response* res); + +typedef struct { + const char* method; + protorpc_handler handler; +} protorpc_router; + +void error_response(protorpc::Response* res, int code, const std::string& message); +void not_found(const protorpc::Request& req, protorpc::Response* res); +void bad_request(const protorpc::Request& req, protorpc::Response* res); + +void calc_add(const protorpc::Request& req, protorpc::Response* res); +void calc_sub(const protorpc::Request& req, protorpc::Response* res); +void calc_mul(const protorpc::Request& req, protorpc::Response* res); +void calc_div(const protorpc::Request& req, protorpc::Response* res); + +void login(const protorpc::Request& req, protorpc::Response* res); + +#endif // HV_PROTO_RPC_ROUTER_H_ diff --git a/external/libhv/libhv-1.3.2/examples/socks5_proxy_server.c b/external/libhv/libhv-1.3.2/examples/socks5_proxy_server.c new file mode 100644 index 0000000..d72581f --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/socks5_proxy_server.c @@ -0,0 +1,408 @@ +/* + * socks5 proxy server + * + * @build: make examples + * + * @proxy_server bin/socks5_proxy_server 1080 + * bin/socks5_proxy_server 1080 username password + * + * @proxy_client curl -v http://www.example.com/ --proxy socks5://127.0.0.1:1080 + * curl -v http://www.example.com/ --proxy socks5://username:password@127.0.0.1:1080 + * + */ + +#include "hv.h" +#include "hloop.h" + +static char proxy_host[64] = "0.0.0.0"; +static int proxy_port = 1080; + +static const char* auth_username = NULL; +static const char* auth_password = NULL; + +#define SOCKS5_VERSION ((uint8_t)5) + +#define SOCKS5_AUTH_VERSION ((uint8_t)1) +#define SOCKS5_AUTH_SUCCESS ((uint8_t)0) +#define SOCKS5_AUTH_FAILURE ((uint8_t)1) + +typedef enum { + NoAuth = 0, + GssApiAuth = 1, + UserPassAuth = 2, +} socks5_auth_method; + +typedef enum { + ConnectCommand = 1, + BindCommand = 2, + AssociateCommand= 3, +} socks5_command; + +typedef enum { + IPv4Addr = 1, + FqdnAddr = 3, + IPv6Addr = 4, +} socks5_addr_type; + +typedef enum { + SuccessReply = 0, + ServerFailure = 1, + RuleFailure = 2, + NetworkUnreachable = 3, + HostUnreachable = 4, + ConnectRefused = 5, + TtlExpired = 6, + CommandNotSupported = 7, + AddrTypeNotSupported= 8, +} socks5_reply_code; + +typedef enum { + s_begin, + s_auth_methods_count, + s_auth_methods, + s_auth_username_len, + s_auth_username, + s_auth_password_len, + s_auth_password, + s_request, + s_dst_addr_type, + s_dst_addr_len, + s_dst_addr, + s_dst_port, + s_upstream, + s_end, +} socks5_state_e; + +typedef struct { + hio_t* io; + socks5_state_e state; + socks5_addr_type addr_type; + sockaddr_u addr; +} socks5_conn_t; + +/* + * workflow: + * hloop_new -> hloop_create_tcp_server -> hloop_run + * on_accept -> HV_ALLOC(socks5_conn_t) -> hio_readbytes(s_auth_methods_count:2) -> + * on_recv -> hio_readbytes(s_auth_methods) -> + * on_recv -> hio_write(auth_method) -> hio_readbytes(s_auth_username_len:2) -> + * on_recv -> hio_readbytes(s_auth_username) -> + * on_recv -> hio_readbytes(s_auth_password_len:1) -> + * on_recv -> hio_readbytes(s_auth_password) -> hio_write(auth_result) -> + * on_recv -> hio_readbytes(s_request:3) -> + * on_recv -> hio_readbytes(addr_type:1) -> + * on_recv -> hio_readbytes(addr_len:1) -> + * on_recv -> hio_readbytes(addr) -> + * on_recv -> hio_readbytes(port:2) -> + * on_recv -> hio_setup_tcp_upstream(io, addr, port) -> + * on_close -> hio_close_upstream -> HV_FREE(socks5_conn_t) + * + */ + +static void on_upstream_connect(hio_t* upstream_io) { + // printf("on_upstream_connect connfd=%d\n", hio_fd(upstream_io)); + socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(upstream_io); + sockaddr_u* localaddr = (sockaddr_u*)hio_localaddr(upstream_io); + uint8_t resp[32] = { SOCKS5_VERSION, SuccessReply, 0, IPv4Addr, 127,0,0,1, 0,80, 0 }; + int resp_len = 3; + if (localaddr->sa.sa_family == AF_INET) { + resp[resp_len++] = IPv4Addr; + memcpy(resp + resp_len, &localaddr->sin.sin_addr, 4); resp_len += 4; + memcpy(resp + resp_len, &localaddr->sin.sin_port, 2); resp_len += 2; + } else if (localaddr->sa.sa_family == AF_INET6) { + resp[resp_len++] = IPv6Addr; + memcpy(resp + resp_len, &localaddr->sin6.sin6_addr, 16); resp_len += 16; + memcpy(resp + resp_len, &localaddr->sin6.sin6_port, 2); resp_len += 2; + } + hio_write(conn->io, resp, resp_len); + hio_setcb_read(upstream_io, hio_write_upstream); + hio_setcb_read(conn->io, hio_write_upstream); + hio_read(conn->io); + hio_read(upstream_io); +} + +static void on_close(hio_t* io) { + // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(io); + if (conn) { + hevent_set_userdata(io, NULL); + HV_FREE(conn); + } + hio_close_upstream(io); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + socks5_conn_t* conn = (socks5_conn_t*)hevent_userdata(io); + const uint8_t* bytes = (uint8_t*)buf; + switch(conn->state) { + case s_begin: + // printf("s_begin\n"); + conn->state = s_auth_methods_count; + case s_auth_methods_count: + // printf("s_auth_methods_count\n"); + { + assert(readbytes == 2); + uint8_t version = bytes[0]; + uint8_t methods_count = bytes[1]; + if (version != SOCKS5_VERSION || methods_count == 0) { + fprintf(stderr, "Unsupprted socks version: %d\n", (int)version); + hio_close(io); + return; + } + conn->state = s_auth_methods; + hio_readbytes(io, methods_count); + } + break; + case s_auth_methods: + // printf("s_auth_methods\n"); + { + // TODO: check auth methos + uint8_t auth_method = NoAuth; + if (auth_username && auth_password) { + auth_method = UserPassAuth; + } else { + // TODO: Implement more auth methods + } + // send auth mothod + uint8_t resp[2] = { SOCKS5_VERSION, NoAuth }; + resp[1] = auth_method; + hio_write(io, resp, 2); + if (auth_method == NoAuth) { + conn->state = s_request; + hio_readbytes(io, 3); + } else if (auth_method == UserPassAuth) { + conn->state = s_auth_username_len; + hio_readbytes(io, 2); + } + } + break; + case s_auth_username_len: + // printf("s_auth_username_len\n"); + { + assert(readbytes == 2); + uint8_t auth_version = bytes[0]; + uint8_t username_len = bytes[1]; + if (auth_version != SOCKS5_AUTH_VERSION || username_len == 0) { + fprintf(stderr, "Unsupported auth version: %d\n", (int)auth_version); + hio_close(io); + return; + } + conn->state = s_auth_username; + hio_readbytes(io, username_len); + } + break; + case s_auth_username: + // printf("s_auth_username\n"); + { + char* username = (char*)bytes; + printf("username=%.*s\n", readbytes, username); + if (readbytes != strlen(auth_username) || + strncmp(username, auth_username, readbytes) != 0) { + fprintf(stderr, "User authentication failed!\n"); + uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_FAILURE }; + hio_write(io, resp, 2); + hio_close(io); + return; + } + conn->state = s_auth_password_len; + hio_readbytes(io, 1); + } + break; + case s_auth_password_len: + // printf("s_auth_password_len\n"); + { + assert(readbytes == 1); + uint8_t password_len = bytes[0]; + if (password_len == 0) { + fprintf(stderr, "Miss password\n"); + uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_FAILURE }; + hio_write(io, resp, 2); + hio_close(io); + return; + } + conn->state = s_auth_password; + hio_readbytes(io, password_len); + } + break; + case s_auth_password: + // printf("s_auth_password\n"); + { + char* password = (char*)bytes; + printf("password=%.*s\n", readbytes, password); + uint8_t resp[2] = { SOCKS5_AUTH_VERSION, SOCKS5_AUTH_SUCCESS }; + if (readbytes != strlen(auth_password) || + strncmp(password, auth_password, readbytes) != 0) { + fprintf(stderr, "User authentication failed!\n"); + resp[1] = SOCKS5_AUTH_FAILURE; + hio_write(io, resp, 2); + hio_close(io); + return; + } + hio_write(io, resp, 2); + conn->state = s_request; + hio_readbytes(io, 3); + } + break; + case s_request: + // printf("s_request\n"); + { + assert(readbytes == 3); + uint8_t version = bytes[0]; + uint8_t cmd = bytes[1]; + if (version != SOCKS5_VERSION || cmd != ConnectCommand) { + // TODO: Implement other commands + fprintf(stderr, "Unsupported command: %d\n", (int)cmd); + hio_close(io); + return; + } + conn->state = s_dst_addr_type; + hio_readbytes(io, 1); + } + break; + case s_dst_addr_type: + // printf("s_dst_addr_type\n"); + { + assert(readbytes == 1); + conn->addr_type = (socks5_addr_type)bytes[0]; + if (conn->addr_type == IPv4Addr) { + conn->state = s_dst_addr; + hio_readbytes(io, 4); + } else if (conn->addr_type == FqdnAddr) { + conn->state = s_dst_addr_len; + hio_readbytes(io, 1); + } else if (conn->addr_type == IPv6Addr) { + conn->state = s_dst_addr; + hio_readbytes(io, 16); + } else { + fprintf(stderr, "Unsupported addr type: %d\n", (int)conn->addr_type); + hio_close(io); + return; + } + } + break; + case s_dst_addr_len: + // printf("s_dst_addr_len\n"); + { + uint8_t addr_len = bytes[0]; + if (addr_len == 0) { + fprintf(stderr, "Miss domain!\n"); + hio_close(io); + return; + } + conn->state = s_dst_addr; + hio_readbytes(io, addr_len); + } + break; + case s_dst_addr: + // printf("s_dst_addr\n"); + { + if (conn->addr_type == IPv4Addr) { + assert(readbytes == 4); + conn->addr.sa.sa_family = AF_INET; + memcpy(&conn->addr.sin.sin_addr, bytes, 4); + } else if (conn->addr_type == IPv6Addr) { + assert(readbytes == 16); + conn->addr.sa.sa_family = AF_INET6; + memcpy(&conn->addr.sin6.sin6_addr, bytes, 16); + } else { + char* host = NULL; + STACK_OR_HEAP_ALLOC(host, readbytes + 1, 256); + memcpy(host, bytes, readbytes); + host[readbytes] = '\0'; + // TODO: async DNS + int ret = ResolveAddr(host, &conn->addr); + STACK_OR_HEAP_FREE(host); + if (ret != 0) { + fprintf(stderr, "Resolve %.*s failed!\n", readbytes, (char*)bytes); + hio_close(io); + return; + } + } + conn->state = s_dst_port; + hio_readbytes(io, 2); + } + break; + case s_dst_port: + // printf("s_dst_port\n"); + { + assert(readbytes == 2); + uint16_t port = ((uint16_t)bytes[0]) << 8 | bytes[1]; + // printf("port=%d\n", port); + sockaddr_set_port(&conn->addr, port); + hloop_t* loop = hevent_loop(io); + // hio_t* upstream_io = hio_setup_tcp_upstream(io, conn->host, conn->port, 0); + // hio_t* upstream_io = hio_create_socket(loop, conn->host, conn->port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + int sockfd = socket(conn->addr.sa.sa_family, SOCK_STREAM, 0); + if (sockfd < 0) { + perror("socket"); + hio_close(io); + return; + } + hio_t* upstream_io = hio_get(loop, sockfd); + assert(upstream_io != NULL); + hio_set_peeraddr(upstream_io, &conn->addr.sa, sockaddr_len(&conn->addr)); + + hevent_set_userdata(upstream_io, conn); + // io <=> upstream_io + hio_setup_upstream(io, upstream_io); + hio_setcb_connect(upstream_io, on_upstream_connect); + hio_setcb_close(upstream_io, hio_close_upstream); + conn->state = s_upstream; + // printf("connect to "); + // SOCKADDR_PRINT(hio_peeraddr(upstream_io)); + hio_connect(upstream_io); + } + break; + case s_upstream: + hio_write_upstream(io, buf, readbytes); + break; + case s_end: + break; + default: + break; + } +} + +static void on_accept(hio_t* io) { + /* + printf("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + hio_setcb_read(io, on_recv); + hio_setcb_close(io, on_close); + + socks5_conn_t* conn = NULL; + HV_ALLOC_SIZEOF(conn); + conn->io = io; + hevent_set_userdata(io, conn); + // start read + conn->state = s_auth_methods_count; + hio_readbytes(io, 2); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s proxy_port [username] [password]\n", argv[0]); + return -10; + } + proxy_port = atoi(argv[1]); + if (argc > 3) { + auth_username = argv[2]; + auth_password = argv[3]; + } + + hloop_t* loop = hloop_new(0); + hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); + if (listenio == NULL) { + return -20; + } + printf("socks5 proxy server listening on %s:%d, listenfd=%d\n", proxy_host, proxy_port, hio_fd(listenio)); + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tcp_chat_server.c b/external/libhv/libhv-1.3.2/examples/tcp_chat_server.c new file mode 100644 index 0000000..324952e --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tcp_chat_server.c @@ -0,0 +1,160 @@ +/* + * tcp chat server + * + * @build make examples + * @server bin/tcp_chat_server 1234 + * @clients bin/nc 127.0.0.1 1234 + * nc 127.0.0.1 1234 + * telnet 127.0.0.1 1234 + */ + +#include "hloop.h" +#include "hsocket.h" +#include "hbase.h" +#include "list.h" + +unpack_setting_t unpack_setting; + +// hloop_create_tcp_server +// on_accept => join +// on_recv => broadcast +// on_close => leave + +typedef struct chatroom_s { + hloop_t* loop; + hio_t* listenio; + int roomid; + struct list_head conns; +} chatroom_t; + +typedef struct connection_s { + hio_t* connio; + char addr[SOCKADDR_STRLEN]; + struct list_node node; +} connection_t; + +static chatroom_t s_chatroom; + +static void join(chatroom_t* room, connection_t* conn); +static void leave(chatroom_t* room, connection_t* conn); +static void broadcast(chatroom_t* room, const char* msg, int msglen); + +void join(chatroom_t* room, connection_t* conn) { + list_add(&conn->node, &room->conns); + + char msg[256] = {0}; + int msglen = 0; + + struct list_node* node; + connection_t* cur; + msglen = snprintf(msg, sizeof(msg), "room[%06d] clients:\r\n", room->roomid); + hio_write(conn->connio, msg, msglen); + list_for_each (node, &room->conns) { + cur = list_entry(node, connection_t, node); + msglen = snprintf(msg, sizeof(msg), "[%s]\r\n", cur->addr); + hio_write(conn->connio, msg, msglen); + } + hio_write(conn->connio, "\r\n", 2); + + msglen = snprintf(msg, sizeof(msg), "client[%s] join room[%06d]\r\n", conn->addr, room->roomid); + broadcast(room, msg, msglen); +} + +void leave(chatroom_t* room, connection_t* conn) { + list_del(&conn->node); + + char msg[256] = {0}; + int msglen = snprintf(msg, sizeof(msg), "client[%s] leave room[%d]\r\n", conn->addr, room->roomid); + broadcast(room, msg, msglen); +} + +void broadcast(chatroom_t* room, const char* msg, int msglen) { + printf("> %.*s", msglen, msg); + struct list_node* node; + connection_t* conn; + list_for_each (node, &room->conns) { + conn = list_entry(node, connection_t, node); + hio_write(conn->connio, msg, msglen); + } +} + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + + connection_t* conn = (connection_t*)hevent_userdata(io); + if (conn) { + hevent_set_userdata(io, NULL); + + leave(&s_chatroom, conn); + HV_FREE(conn); + } +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + printf("< %.*s", readbytes, (char*)buf); + + // broadcast + connection_t* conn = (connection_t*)hevent_userdata(io); + assert(conn != NULL); + char msg[256] = {0}; + int msglen = snprintf(msg, sizeof(msg), "client[%s] say: %.*s", conn->addr, readbytes, (char*)buf); + broadcast(&s_chatroom, msg, msglen); +} + +static void on_accept(hio_t* io) { + printf("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_set_unpack(io, &unpack_setting); + hio_read_start(io); + + // free on_close + connection_t* conn = NULL; + HV_ALLOC_SIZEOF(conn); + conn->connio = io; + strcpy(conn->addr, peeraddrstr); + hevent_set_userdata(io, conn); + join(&s_chatroom, conn); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + memset(&unpack_setting, 0, sizeof(unpack_setting_t)); + unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + unpack_setting.mode = UNPACK_BY_DELIMITER; + unpack_setting.delimiter[0] = '\n'; + unpack_setting.delimiter_bytes = 1; + + hloop_t* loop = hloop_new(0); + hio_t* listenio = hloop_create_tcp_server(loop, "0.0.0.0", port, on_accept); + if (listenio == NULL) { + return -20; + } + printf("listenfd=%d\n", hio_fd(listenio)); + + s_chatroom.loop = loop; + s_chatroom.listenio = listenio; + s_chatroom.roomid = hv_rand(100000, 999999); + list_init(&s_chatroom.conns); + + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tcp_client_test.c b/external/libhv/libhv-1.3.2/examples/tcp_client_test.c new file mode 100644 index 0000000..9572937 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tcp_client_test.c @@ -0,0 +1,251 @@ +/* + * tcp client demo + * + * @build make examples + * @server bin/tcp_echo_server 1234 + * @client bin/tcp_client_test 127.0.0.1 1234 + * + */ + +#include "hloop.h" +#include "hssl.h" +#include "hmutex.h" + +#include "hbase.h" +#include "herr.h" + +#define TEST_SSL 0 +#define TEST_UNPACK 0 +#define TEST_RECONNECT 1 + +// @see mqtt/mqtt_client.h +typedef struct tcp_client_s { + // connect: host:port + char host[256]; + int port; + int connect_timeout; // ms + // reconnect + reconn_setting_t* reconn_setting; + // flags + unsigned char ssl: 1; // Read Only + unsigned char alloced_ssl_ctx: 1; // intern + unsigned char connected : 1; + // privdata + hloop_t* loop; + hio_t* io; + htimer_t* reconn_timer; + // SSL/TLS + hssl_ctx_t ssl_ctx; + // thread-safe + hmutex_t mutex_; + // ... +} tcp_client_t; + +static tcp_client_t* tcp_client_new(hloop_t* loop DEFAULT(NULL)); +static void tcp_client_run (tcp_client_t* cli); +static void tcp_client_stop(tcp_client_t* cli); +static void tcp_client_free(tcp_client_t* cli); + +// SSL/TLS +static int tcp_client_set_ssl_ctx(tcp_client_t* cli, hssl_ctx_t ssl_ctx); +static int tcp_client_new_ssl_ctx(tcp_client_t* cli, hssl_ctx_opt_t* opt); + +// reconnect +static int tcp_client_set_reconnect(tcp_client_t* cli, reconn_setting_t* reconn); +static int tcp_client_reconnect(tcp_client_t* cli); + +static void tcp_client_set_connnect_timeout(tcp_client_t* cli, int timeout_ms); +static int tcp_client_connect(tcp_client_t* cli, const char* host, int port, int ssl); +static int tcp_client_disconnect(tcp_client_t* cli); +static bool tcp_client_is_connected(tcp_client_t* cli); + +static int tcp_client_send(tcp_client_t* cli, const void* buf, int len); + +static void reconnect_timer_cb(htimer_t* timer) { + tcp_client_t* cli = (tcp_client_t*)hevent_userdata(timer); + if (cli == NULL) return; + cli->reconn_timer = NULL; + tcp_client_reconnect(cli); +} + +static void on_close(hio_t* io) { + printf("onclose: connfd=%d error=%d\n", hio_fd(io), hio_error(io)); + tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); + cli->connected = 0; + // reconnect + if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { + uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); + printf("reconnect cnt=%d, delay=%d ...\n", cli->reconn_setting->cur_retry_cnt, cli->reconn_setting->cur_delay); + cli->reconn_timer = htimer_add(cli->loop, reconnect_timer_cb, delay, 1); + hevent_set_userdata(cli->reconn_timer, cli); + } +} + +static void on_message(hio_t* io, void* buf, int len) { + printf("onmessage: %.*s\n", len, (char*)buf); + tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); + // ... +} + +static void on_connect(hio_t* io) { + printf("onconnect: connfd=%d\n", hio_fd(io)); + tcp_client_t* cli = (tcp_client_t*)hevent_userdata(io); + cli->connected = 1; + +#if TEST_UNPACK + static unpack_setting_t s_unpack_setting; + s_unpack_setting.mode = UNPACK_BY_DELIMITER; + s_unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + s_unpack_setting.delimiter_bytes = 2; + s_unpack_setting.delimiter[0] = '\r'; + s_unpack_setting.delimiter[1] = '\n'; + hio_set_unpack(io, &s_unpack_setting); +#endif + + hio_write(io, "hello\r\n", 7); + + hio_setcb_read(io, on_message); + hio_read(io); +} + +// hloop_new -> malloc(tcp_client_t) +tcp_client_t* tcp_client_new(hloop_t* loop) { + if (loop == NULL) { + loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + if (loop == NULL) return NULL; + } + tcp_client_t* cli = NULL; + HV_ALLOC_SIZEOF(cli); + if (cli == NULL) return NULL; + cli->loop = loop; + hmutex_init(&cli->mutex_); + return cli; +} + +// hloop_free -> free(tcp_client_t) +void tcp_client_free(tcp_client_t* cli) { + if (!cli) return; + hmutex_destroy(&cli->mutex_); + if (cli->ssl_ctx && cli->alloced_ssl_ctx) { + hssl_ctx_free(cli->ssl_ctx); + cli->ssl_ctx = NULL; + } + HV_FREE(cli->reconn_setting); + HV_FREE(cli); +} + +void tcp_client_run (tcp_client_t* cli) { + if (!cli || !cli->loop) return; + hloop_run(cli->loop); +} + +void tcp_client_stop(tcp_client_t* cli) { + if (!cli || !cli->loop) return; + hloop_stop(cli->loop); +} + +int tcp_client_set_ssl_ctx(tcp_client_t* cli, hssl_ctx_t ssl_ctx) { + cli->ssl_ctx = ssl_ctx; + return 0; +} + +// hssl_ctx_new(opt) -> tcp_client_set_ssl_ctx +int tcp_client_new_ssl_ctx(tcp_client_t* cli, hssl_ctx_opt_t* opt) { + opt->endpoint = HSSL_CLIENT; + hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); + if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; + cli->alloced_ssl_ctx = true; + return tcp_client_set_ssl_ctx(cli, ssl_ctx); +} + +int tcp_client_set_reconnect(tcp_client_t* cli, reconn_setting_t* reconn) { + if (reconn == NULL) { + HV_FREE(cli->reconn_setting); + return 0; + } + if (cli->reconn_setting == NULL) { + HV_ALLOC_SIZEOF(cli->reconn_setting); + } + *cli->reconn_setting = *reconn; + return 0; +} + +int tcp_client_reconnect(tcp_client_t* cli) { + tcp_client_connect(cli, cli->host, cli->port, cli->ssl); + return 0; +} + +int tcp_client_connect(tcp_client_t* cli, const char* host, int port, int ssl) { + if (!cli) return -1; + hv_strncpy(cli->host, host, sizeof(cli->host)); + cli->port = port; + cli->ssl = ssl; + hio_t* io = hio_create_socket(cli->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (io == NULL) return -1; + if (ssl) { + if (cli->ssl_ctx) { + hio_set_ssl_ctx(io, cli->ssl_ctx); + } + hio_enable_ssl(io); + } + if (cli->connect_timeout > 0) { + hio_set_connect_timeout(io, cli->connect_timeout); + } + cli->io = io; + hevent_set_userdata(io, cli); + hio_setcb_connect(io, on_connect); + hio_setcb_close(io, on_close); + return hio_connect(io); +} + +int tcp_client_disconnect(tcp_client_t* cli) { + if (!cli || !cli->io) return -1; + // cancel reconnect first + tcp_client_set_reconnect(cli, NULL); + return hio_close(cli->io); +} + +bool tcp_client_is_connected(tcp_client_t* cli) { + return cli && cli->connected; +} + +int tcp_client_send(tcp_client_t* cli, const void* buf, int len) { + if (!cli || !cli->io || !buf || len == 0) return -1; + if (!cli->connected) return -2; + // thread-safe + hmutex_lock(&cli->mutex_); + int nwrite = hio_write(cli->io, buf, len); + hmutex_unlock(&cli->mutex_); + return nwrite; +} + +int main(int argc, char** argv) { + if (argc < 3) { + printf("Usage: %s host port\n", argv[0]); + return -10; + } + const char* host = argv[1]; + int port = atoi(argv[2]); + + tcp_client_t* cli = tcp_client_new(NULL); + if (!cli) return -20; + +#if TEST_RECONNECT + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + tcp_client_set_reconnect(cli, &reconn); +#endif + + int ssl = 0; +#if TEST_SSL + ssl = 1; +#endif + tcp_client_connect(cli, host, port, ssl); + + tcp_client_run(cli); + tcp_client_free(cli); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tcp_echo_server.c b/external/libhv/libhv-1.3.2/examples/tcp_echo_server.c new file mode 100644 index 0000000..f48788f --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tcp_echo_server.c @@ -0,0 +1,143 @@ +/* + * tcp echo server + * + * @build make examples + * @server bin/tcp_echo_server 1234 + * @client bin/nc 127.0.0.1 1234 + * nc 127.0.0.1 1234 + * telnet 127.0.0.1 1234 + */ + +#include "hloop.h" +#include "hsocket.h" +#include "hssl.h" + +/* + * @test ssl_server + * #define TEST_SSL 1 + * + * @build ./configure --with-openssl && make clean && make + * @server bin/tcp_echo_server 1234 + * @client bin/nc -s 127.0.0.1 1234 + * + */ +#define TEST_SSL 0 +#define TEST_READ_ONCE 0 +#define TEST_READLINE 0 +#define TEST_READSTRING 0 +#define TEST_READBYTES 0 +#define TEST_READ_STOP 0 +#define TEST_UNPACK 0 + +#if TEST_UNPACK +static unpack_setting_t unpack_setting; +#endif + +// hloop_create_tcp_server -> on_accept -> hio_read -> on_recv -> hio_write + +static void on_close(hio_t* io) { + printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + printf("< %.*s", readbytes, (char*)buf); + // echo + printf("> %.*s", readbytes, (char*)buf); + hio_write(io, buf, readbytes); + +#if TEST_READ_STOP + hio_read_stop(io); +#elif TEST_READ_ONCE + hio_read_once(io); +#elif TEST_READLINE + hio_readline(io); +#elif TEST_READSTRING + hio_readstring(io); +#elif TEST_READBYTES + hio_readbytes(io, TEST_READBYTES); +#endif +} + +static void on_accept(hio_t* io) { + printf("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + +#if TEST_UNPACK + hio_set_unpack(io, &unpack_setting); +#endif + +#if TEST_READ_ONCE + hio_read_once(io); +#elif TEST_READLINE + hio_readline(io); +#elif TEST_READSTRING + hio_readstring(io); +#elif TEST_READBYTES + hio_readbytes(io, TEST_READBYTES); +#else + hio_read_start(io); +#endif +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port|path\n", argv[0]); + return -10; + } + const char* host = "0.0.0.0"; + int port = atoi(argv[1]); +#if ENABLE_UDS + if (port == 0) { + host = argv[1]; + port = -1; + } +#endif + +#if TEST_UNPACK + memset(&unpack_setting, 0, sizeof(unpack_setting_t)); + unpack_setting.package_max_length = DEFAULT_PACKAGE_MAX_LENGTH; + unpack_setting.mode = UNPACK_BY_DELIMITER; + unpack_setting.delimiter[0] = '\r'; + unpack_setting.delimiter[1] = '\n'; + unpack_setting.delimiter_bytes = 2; +#endif + + hloop_t* loop = hloop_new(0); +#if TEST_SSL + hio_t* listenio = hloop_create_ssl_server(loop, host, port, on_accept); +#else + hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); +#endif + if (listenio == NULL) { + return -20; + } +#if TEST_SSL + hssl_ctx_opt_t ssl_param; + memset(&ssl_param, 0, sizeof(ssl_param)); + ssl_param.crt_file = "cert/server.crt"; + ssl_param.key_file = "cert/server.key"; + ssl_param.endpoint = HSSL_SERVER; + if (hio_new_ssl_ctx(listenio, &ssl_param) != 0) { + fprintf(stderr, "hssl_ctx_new failed!\n"); + return -30; + } +#endif + + printf("listenfd=%d\n", hio_fd(listenio)); + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tcp_proxy_server.c b/external/libhv/libhv-1.3.2/examples/tcp_proxy_server.c new file mode 100644 index 0000000..ccdfd20 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tcp_proxy_server.c @@ -0,0 +1,86 @@ +/* + * tcp proxy server + * + * @build: make clean && make examples WITH_OPENSSL=yes + * @http_server: bin/httpd -s restart -d + * @proxy_server: bin/tcp_proxy_server 1080 127.0.0.1:8080 + * bin/tcp_proxy_server 1080 127.0.0.1:8443 + * bin/tcp_proxy_server 1080 www.baidu.com + * bin/tcp_proxy_server 1080 www.baidu.com:443 + * @client: bin/curl -v 127.0.0.1:1080 + * bin/nc 127.0.0.1 1080 + * > GET / HTTP/1.1 + * > Connection: close + * > [Enter] + * > GET / HTTP/1.1 + * > Connection: keep-alive + * > [Enter] + * + * @benchmark: sudo apt install iperf + * iperf -s -p 5001 + * bin/tcp_proxy_server 1212 127.0.0.1:5001 + * iperf -c 127.0.0.1 -p 5001 -l 8K + * iperf -c 127.0.0.1 -p 1212 -l 8K + */ + +#include "hloop.h" +#include "hsocket.h" + +static char proxy_host[64] = "0.0.0.0"; +static int proxy_port = 1080; +static int proxy_ssl = 0; + +static char backend_host[64] = "127.0.0.1"; +static int backend_port = 80; +static int backend_ssl = 0; + +// hloop_create_tcp_server -> on_accept -> hio_setup_tcp_upstream + +static void on_accept(hio_t* io) { + /* + printf("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + if (backend_port % 1000 == 443) backend_ssl = 1; + hio_setup_tcp_upstream(io, backend_host, backend_port, backend_ssl); +} + +int main(int argc, char** argv) { + if (argc < 3) { + printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]); + return -10; + } + proxy_port = atoi(argv[1]); + if (proxy_port % 1000 == 443) proxy_ssl = 1; + char* pos = strchr(argv[2], ':'); + if (pos) { + int len = pos - argv[2]; + if (len > 0) { + memcpy(backend_host, argv[2], len); + backend_host[len] = '\0'; + } + backend_port = atoi(pos + 1); + } else { + strncpy(backend_host, argv[2], sizeof(backend_host)); + } + if (backend_port == 0) backend_port = 80; + printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port); + + hloop_t* loop = hloop_new(0); + hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); + if (listenio == NULL) { + return -20; + } + printf("listenfd=%d\n", hio_fd(listenio)); + if (proxy_ssl) { + hio_enable_ssl(listenio); + } + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tinyhttpd.c b/external/libhv/libhv-1.3.2/examples/tinyhttpd.c new file mode 100644 index 0000000..5aa6693 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tinyhttpd.c @@ -0,0 +1,475 @@ +/* + * tinyhttpd tiny http server + * + * @build make examples + * + * @server bin/tinyhttpd 8000 + * + * @client bin/curl -v http://127.0.0.1:8000/ + * bin/curl -v http://127.0.0.1:8000/ping + * bin/curl -v http://127.0.0.1:8000/echo -d "hello,world!" + * + * @webbench bin/wrk http://127.0.0.1:8000/ping + * + */ + +#include "hv.h" +#include "hloop.h" + +/* + * workflow: + * hloop_new -> hloop_create_tcp_server -> hloop_run -> + * on_accept -> HV_ALLOC(http_conn_t) -> hio_readline -> + * on_recv -> parse_http_request_line -> hio_readline -> + * on_recv -> parse_http_head -> ... -> hio_readbytes(content_length) -> + * on_recv -> on_request -> http_reply-> hio_write -> hio_close -> + * on_close -> HV_FREE(http_conn_t) + * + */ + +static const char* host = "0.0.0.0"; +static int port = 8000; +static int thread_num = 1; +static hloop_t* accept_loop = NULL; +static hloop_t** worker_loops = NULL; + +#define HTTP_KEEPALIVE_TIMEOUT 60000 // ms +#define HTTP_MAX_URL_LENGTH 256 +#define HTTP_MAX_HEAD_LENGTH 1024 + +#define HTML_TAG_BEGIN "

" +#define HTML_TAG_END "

" + +// status_message +#define HTTP_OK "OK" +#define NOT_FOUND "Not Found" +#define NOT_IMPLEMENTED "Not Implemented" + +// Content-Type +#define TEXT_PLAIN "text/plain" +#define TEXT_HTML "text/html" + +typedef enum { + s_begin, + s_first_line, + s_request_line = s_first_line, + s_status_line = s_first_line, + s_head, + s_head_end, + s_body, + s_end +} http_state_e; + +typedef struct { + // first line + int major_version; + int minor_version; + union { + // request line + struct { + char method[32]; + char path[HTTP_MAX_URL_LENGTH]; + }; + // status line + struct { + int status_code; + char status_message[64]; + }; + }; + // headers + char host[64]; + int content_length; + char content_type[64]; + unsigned keepalive: 1; +// char head[HTTP_MAX_HEAD_LENGTH]; +// int head_len; + // body + char* body; + int body_len; // body_len = content_length +} http_msg_t; + +typedef struct { + hio_t* io; + http_state_e state; + http_msg_t request; + http_msg_t response; + // for http_serve_file + FILE* fp; + hbuf_t filebuf; +} http_conn_t; + +static char s_date[32] = {0}; +static void update_date(htimer_t* timer) { + uint64_t now = hloop_now(hevent_loop(timer)); + gmtime_fmt(now, s_date); +} + +static int http_response_dump(http_msg_t* msg, char* buf, int len) { + int offset = 0; + // status line + offset += snprintf(buf + offset, len - offset, "HTTP/%d.%d %d %s\r\n", msg->major_version, msg->minor_version, msg->status_code, msg->status_message); + // headers + offset += snprintf(buf + offset, len - offset, "Server: libhv/%s\r\n", hv_version()); + offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close"); + if (msg->content_length > 0) { + offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length); + } + if (*msg->content_type) { + offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type); + } + if (*s_date) { + offset += snprintf(buf + offset, len - offset, "Date: %s\r\n", s_date); + } + // TODO: Add your headers + offset += snprintf(buf + offset, len - offset, "\r\n"); + // body + if (msg->body && msg->content_length > 0) { + memcpy(buf + offset, msg->body, msg->content_length); + offset += msg->content_length; + } + return offset; +} + +static int http_reply(http_conn_t* conn, + int status_code, const char* status_message, + const char* content_type, + const char* body, int body_len) { + http_msg_t* req = &conn->request; + http_msg_t* resp = &conn->response; + resp->major_version = req->major_version; + resp->minor_version = req->minor_version; + resp->status_code = status_code; + if (status_message) strncpy(resp->status_message, status_message, sizeof(req->status_message) - 1); + if (content_type) strncpy(resp->content_type, content_type, sizeof(req->content_type) - 1); + resp->keepalive = req->keepalive; + if (body) { + if (body_len <= 0) body_len = strlen(body); + resp->content_length = body_len; + resp->body = (char*)body; + } + char* buf = NULL; + STACK_OR_HEAP_ALLOC(buf, HTTP_MAX_HEAD_LENGTH + resp->content_length, HTTP_MAX_HEAD_LENGTH + 1024); + int msglen = http_response_dump(resp, buf, HTTP_MAX_HEAD_LENGTH + resp->content_length); + int nwrite = hio_write(conn->io, buf, msglen); + STACK_OR_HEAP_FREE(buf); + return nwrite < 0 ? nwrite : msglen; +} + +static void http_send_file(http_conn_t* conn) { + if (!conn || !conn->fp) return; + // alloc filebuf + if (!conn->filebuf.base) { + conn->filebuf.len = 4096; + HV_ALLOC(conn->filebuf, conn->filebuf.len); + } + char* filebuf = conn->filebuf.base; + size_t filebuflen = conn->filebuf.len; + // read file + int nread = fread(filebuf, 1, filebuflen, conn->fp); + if (nread <= 0) { + // eof or error + hio_close(conn->io); + return; + } + // send file + hio_write(conn->io, filebuf, nread); +} + +static void on_write(hio_t* io, const void* buf, int writebytes) { + if (!io) return; + if (!hio_write_is_complete(io)) return; + http_conn_t* conn = (http_conn_t*)hevent_userdata(io); + http_send_file(conn); +} + +static int http_serve_file(http_conn_t* conn) { + http_msg_t* req = &conn->request; + http_msg_t* resp = &conn->response; + // GET / HTTP/1.1\r\n + const char* filepath = req->path + 1; + // homepage + if (*filepath == '\0') { + filepath = "index.html"; + } + // open file + conn->fp = fopen(filepath, "rb"); + if (!conn->fp) { + http_reply(conn, 404, NOT_FOUND, TEXT_HTML, HTML_TAG_BEGIN NOT_FOUND HTML_TAG_END, 0); + return 404; + } + // send head + size_t filesize = hv_filesize(filepath); + resp->content_length = filesize; + const char* suffix = hv_suffixname(filepath); + const char* content_type = NULL; + if (strcmp(suffix, "html") == 0) { + content_type = TEXT_HTML; + } else { + // TODO: set content_type by suffix + } + hio_setcb_write(conn->io, on_write); + int nwrite = http_reply(conn, 200, "OK", content_type, NULL, 0); + if (nwrite < 0) return nwrite; // disconnected + return 200; +} + +static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) { + // GET / HTTP/1.1 + http_msg_t* req = &conn->request; + sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version); + if (req->major_version != 1) return false; + if (req->minor_version == 1) req->keepalive = 1; + // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version); + return true; +} + +static bool parse_http_head(http_conn_t* conn, char* buf, int len) { + http_msg_t* req = &conn->request; + // Content-Type: text/html + const char* key = buf; + const char* val = buf; + char* delim = strchr(buf, ':'); + if (!delim) return false; + *delim = '\0'; + val = delim + 1; + // trim space + while (*val == ' ') ++val; + // printf("%s: %s\r\n", key, val); + if (stricmp(key, "Content-Length") == 0) { + req->content_length = atoi(val); + } else if (stricmp(key, "Content-Type") == 0) { + strncpy(req->content_type, val, sizeof(req->content_type) - 1); + } else if (stricmp(key, "Connection") == 0) { + if (stricmp(val, "close") == 0) { + req->keepalive = 0; + } + } else { + // TODO: save other head + } + return true; +} + +static int on_request(http_conn_t* conn) { + http_msg_t* req = &conn->request; + // TODO: router + if (strcmp(req->method, "GET") == 0) { + // GET /ping HTTP/1.1\r\n + if (strcmp(req->path, "/ping") == 0) { + http_reply(conn, 200, "OK", TEXT_PLAIN, "pong", 4); + return 200; + } else { + // TODO: Add handler for your path + } + return http_serve_file(conn); + } else if (strcmp(req->method, "POST") == 0) { + // POST /echo HTTP/1.1\r\n + if (strcmp(req->path, "/echo") == 0) { + http_reply(conn, 200, "OK", req->content_type, req->body, req->content_length); + return 200; + } else { + // TODO: Add handler for your path + } + } else { + // TODO: handle other method + } + http_reply(conn, 501, NOT_IMPLEMENTED, TEXT_HTML, HTML_TAG_BEGIN NOT_IMPLEMENTED HTML_TAG_END, 0); + return 501; +} + +static void on_close(hio_t* io) { + // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + http_conn_t* conn = (http_conn_t*)hevent_userdata(io); + if (conn) { + if (conn->fp) { + // close file + fclose(conn->fp); + conn->fp = NULL; + } + // free filebuf + HV_FREE(conn->filebuf.base); + HV_FREE(conn); + hevent_set_userdata(io, NULL); + } +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + char* str = (char*)buf; + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + // printf("%.*s", readbytes, str); + http_conn_t* conn = (http_conn_t*)hevent_userdata(io); + http_msg_t* req = &conn->request; + switch (conn->state) { + case s_begin: + // printf("s_begin"); + conn->state = s_first_line; + case s_first_line: + // printf("s_first_line\n"); + if (readbytes < 2) { + fprintf(stderr, "Not match \r\n!"); + hio_close(io); + return; + } + str[readbytes - 2] = '\0'; + if (parse_http_request_line(conn, str, readbytes - 2) == false) { + fprintf(stderr, "Failed to parse http request line:\n%s\n", str); + hio_close(io); + return; + } + // start read head + conn->state = s_head; + hio_readline(io); + break; + case s_head: + // printf("s_head\n"); + if (readbytes < 2) { + fprintf(stderr, "Not match \r\n!"); + hio_close(io); + return; + } + if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') { + conn->state = s_head_end; + } else { + str[readbytes - 2] = '\0'; + if (parse_http_head(conn, str, readbytes - 2) == false) { + fprintf(stderr, "Failed to parse http head:\n%s\n", str); + hio_close(io); + return; + } + hio_readline(io); + break; + } + case s_head_end: + // printf("s_head_end\n"); + if (req->content_length == 0) { + conn->state = s_end; + goto s_end; + } else { + // start read body + conn->state = s_body; + // WARN: too large content_length should read multiple times! + hio_readbytes(io, req->content_length); + break; + } + case s_body: + // printf("s_body\n"); + req->body = str; + req->body_len += readbytes; + if (req->body_len == req->content_length) { + conn->state = s_end; + } else { + // WARN: too large content_length should be handled by streaming! + break; + } + case s_end: +s_end: + // printf("s_end\n"); + // received complete request + on_request(conn); + if (hio_is_closed(io)) return; + if (req->keepalive) { + // Connection: keep-alive\r\n + // reset and receive next request + memset(&conn->request, 0, sizeof(http_msg_t)); + memset(&conn->response, 0, sizeof(http_msg_t)); + conn->state = s_first_line; + hio_readline(io); + } else { + // Connection: close\r\n + hio_close(io); + } + break; + default: break; + } +} + +static void new_conn_event(hevent_t* ev) { + hloop_t* loop = ev->loop; + hio_t* io = (hio_t*)hevent_userdata(ev); + hio_attach(loop, io); + + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("tid=%ld connfd=%d [%s] <= [%s]\n", + (long)hv_gettid(), + (int)hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT); + + http_conn_t* conn = NULL; + HV_ALLOC_SIZEOF(conn); + conn->io = io; + hevent_set_userdata(io, conn); + // start read first line + conn->state = s_first_line; + hio_readline(io); +} + +static hloop_t* get_next_loop() { + static int s_cur_index = 0; + if (s_cur_index == thread_num) { + s_cur_index = 0; + } + return worker_loops[s_cur_index++]; +} + +static void on_accept(hio_t* io) { + hio_detach(io); + + hloop_t* worker_loop = get_next_loop(); + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.loop = worker_loop; + ev.cb = new_conn_event; + ev.userdata = io; + hloop_post_event(worker_loop, &ev); +} + +static HTHREAD_ROUTINE(worker_thread) { + hloop_t* loop = (hloop_t*)userdata; + hloop_run(loop); + return 0; +} + +static HTHREAD_ROUTINE(accept_thread) { + hloop_t* loop = (hloop_t*)userdata; + hio_t* listenio = hloop_create_tcp_server(loop, host, port, on_accept); + if (listenio == NULL) { + exit(1); + } + printf("tinyhttpd listening on %s:%d, listenfd=%d, thread_num=%d\n", + host, port, hio_fd(listenio), thread_num); + // NOTE: add timer to update date every 1s + htimer_add(loop, update_date, 1000, INFINITE); + hloop_run(loop); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port [thread_num]\n", argv[0]); + return -10; + } + port = atoi(argv[1]); + if (argc > 2) { + thread_num = atoi(argv[2]); + } else { + thread_num = get_ncpu(); + } + if (thread_num == 0) thread_num = 1; + + worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); + for (int i = 0; i < thread_num; ++i) { + worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); + hthread_create(worker_thread, worker_loops[i]); + } + + accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + accept_thread(accept_loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/tinyproxyd.c b/external/libhv/libhv-1.3.2/examples/tinyproxyd.c new file mode 100644 index 0000000..fe9ba64 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/tinyproxyd.c @@ -0,0 +1,479 @@ +/* + * tinyproxyd tiny http proxy server + * + * @build make examples + * + * @http_server bin/tinyhttpd 8000 + * @proxy_server bin/tinyproxyd 1080 + * + * @proxy_client bin/curl -v www.httpbin.org/get --http-proxy 127.0.0.1:1080 + * bin/curl -v www.httpbin.org/post -d hello --http-proxy 127.0.0.1:1080 + * curl -v www.httpbin.org/get --proxy http://127.0.0.1:1080 + * curl -v www.httpbin.org/post -d hello --proxy http://127.0.0.1:1080 + * + */ + +#include "hv.h" +#include "hloop.h" + +/* + * workflow: + * hloop_new -> hloop_create_tcp_server -> hloop_run -> + * on_accept -> HV_ALLOC(http_conn_t) -> hio_readline -> + * on_recv -> parse_http_request_line -> hio_readline -> + * on_recv -> parse_http_head -> ... -> hio_readline -> + * on_head_end -> hio_setup_upstream -> + * on_upstream_connect -> hio_write_upstream(head) -> + * on_body -> hio_write_upstream(body) -> + * on_upstream_close -> hio_close -> + * on_close -> HV_FREE(http_conn_t) + * + */ + +static char proxy_host[64] = "0.0.0.0"; +static int proxy_port = 1080; +static int proxy_ssl = 0; + +static int thread_num = 1; +static hloop_t* accept_loop = NULL; +static hloop_t** worker_loops = NULL; + +#define HTTP_KEEPALIVE_TIMEOUT 60000 // ms +#define HTTP_MAX_URL_LENGTH 256 +#define HTTP_MAX_HEAD_LENGTH 1024 + +typedef enum { + s_begin, + s_first_line, + s_request_line = s_first_line, + s_status_line = s_first_line, + s_head, + s_head_end, + s_body, + s_end +} http_state_e; + +typedef struct { + // first line + int major_version; + int minor_version; + union { + // request line + struct { + char method[32]; + char path[HTTP_MAX_URL_LENGTH]; + }; + // status line + struct { + int status_code; + char status_message[64]; + }; + }; + // headers + char host[64]; + int content_length; + char content_type[64]; + unsigned keepalive: 1; + unsigned proxy: 1; + char head[HTTP_MAX_HEAD_LENGTH]; + int head_len; + // body + char* body; + int body_len; // body_len = content_length +} http_msg_t; + +typedef struct { + hio_t* io; + http_state_e state; + http_msg_t request; +// http_msg_t response; +} http_conn_t; + +static int http_request_dump(http_conn_t* conn, char* buf, int len) { + http_msg_t* msg = &conn->request; + int offset = 0; + // request line + const char* path = msg->path; + if (msg->proxy) { + const char* pos = strstr(msg->path, "://"); + pos = pos ? pos + 3 : msg->path; + path = strchr(pos, '/'); + } + if (path == NULL) path = "/"; + offset += snprintf(buf + offset, len - offset, "%s %s HTTP/%d.%d\r\n", msg->method, path, msg->major_version, msg->minor_version); + // headers + if (msg->proxy) { + if (msg->head_len) { + memcpy(buf + offset, msg->head, msg->head_len); + offset += msg->head_len; + } + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + SOCKADDR_STR(hio_peeraddr(conn->io), peeraddrstr); + offset += snprintf(buf + offset, len - offset, "X-Origin-IP: %s\r\n", peeraddrstr); + } else { + offset += snprintf(buf + offset, len - offset, "Connection: %s\r\n", msg->keepalive ? "keep-alive" : "close"); + if (msg->content_length > 0) { + offset += snprintf(buf + offset, len - offset, "Content-Length: %d\r\n", msg->content_length); + } + if (*msg->content_type) { + offset += snprintf(buf + offset, len - offset, "Content-Type: %s\r\n", msg->content_type); + } + } + // TODO: Add your headers + offset += snprintf(buf + offset, len - offset, "\r\n"); + // body + if (msg->body && msg->content_length > 0) { + memcpy(buf + offset, msg->body, msg->content_length); + offset += msg->content_length; + } + return offset; +} + +static bool parse_http_request_line(http_conn_t* conn, char* buf, int len) { + // GET / HTTP/1.1 + http_msg_t* req = &conn->request; + sscanf(buf, "%s %s HTTP/%d.%d", req->method, req->path, &req->major_version, &req->minor_version); + if (req->major_version != 1) return false; + if (req->minor_version == 1) req->keepalive = 1; + // printf("%s %s HTTP/%d.%d\r\n", req->method, req->path, req->major_version, req->minor_version); + return true; +} + +static bool parse_http_head(http_conn_t* conn, char* buf, int len) { + http_msg_t* req = &conn->request; + // Content-Type: text/html + const char* key = buf; + const char* val = buf; + char* delim = strchr(buf, ':'); + if (!delim) return false; + *delim = '\0'; + val = delim + 1; + // trim space + while (*val == ' ') ++val; + // printf("%s: %s\r\n", key, val); + if (stricmp(key, "Host") == 0) { + strncpy(req->host, val, sizeof(req->host) - 1); + } else if (stricmp(key, "Content-Length") == 0) { + req->content_length = atoi(val); + } else if (stricmp(key, "Content-Type") == 0) { + strncpy(req->content_type, val, sizeof(req->content_type) - 1); + } else if (stricmp(key, "Connection") == 0 || stricmp(key, "Proxy-Connection") == 0) { + if (stricmp(val, "close") == 0) { + req->keepalive = 0; + } + } + return true; +} + +static void on_upstream_connect(hio_t* upstream_io) { + // printf("on_upstream_connect\n"); + http_conn_t* conn = (http_conn_t*)hevent_userdata(upstream_io); + http_msg_t* req = &conn->request; + // send head + char stackbuf[HTTP_MAX_HEAD_LENGTH + 1024] = {0}; + char* buf = stackbuf; + int buflen = sizeof(stackbuf); + int msglen = http_request_dump(conn, buf, buflen); + hio_write(upstream_io, buf, msglen); + if (conn->state != s_end) { + // start recv body then upstream + hio_read_start(conn->io); + } else { + if (req->keepalive) { + // Connection: keep-alive\r\n + // reset and receive next request + memset(&conn->request, 0, sizeof(http_msg_t)); + // memset(&conn->response, 0, sizeof(http_msg_t)); + conn->state = s_first_line; + hio_readline(conn->io); + } + } + // start recv response + hio_read_start(upstream_io); +} + +static int on_head_end(http_conn_t* conn) { + http_msg_t* req = &conn->request; + if (req->host[0] == '\0') { + fprintf(stderr, "No Host header!\n"); + return -1; + } + char backend_host[64] = {0}; + strcpy(backend_host, req->host); + int backend_port = 80; + char* pos = strchr(backend_host, ':'); + if (pos) { + *pos = '\0'; + backend_port = atoi(pos + 1); + } + if (backend_port == proxy_port && + (strcmp(backend_host, proxy_host) == 0 || + strcmp(backend_host, "localhost") == 0 || + strcmp(backend_host, "127.0.0.1") == 0)) { + req->proxy = 0; + return 0; + } + // NOTE: blew for proxy + req->proxy = 1; + int backend_ssl = strncmp(req->path, "https", 5) == 0 ? 1 : 0; + // printf("upstream %s:%d\n", backend_host, backend_port); + hloop_t* loop = hevent_loop(conn->io); + // hio_t* upstream_io = hio_setup_tcp_upstream(conn->io, backend_host, backend_port, backend_ssl); + hio_t* upstream_io = hio_create_socket(loop, backend_host, backend_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (upstream_io == NULL) { + fprintf(stderr, "Failed to upstream %s:%d!\n", backend_host, backend_port); + return -3; + } + if (backend_ssl) { + hio_enable_ssl(upstream_io); + } + hevent_set_userdata(upstream_io, conn); + hio_setup_upstream(conn->io, upstream_io); + hio_setcb_read(upstream_io, hio_write_upstream); + hio_setcb_close(upstream_io, hio_close_upstream); + hio_setcb_connect(upstream_io, on_upstream_connect); + hio_connect(upstream_io); + return 0; +} + +static int on_body(http_conn_t* conn, void* buf, int readbytes) { + http_msg_t* req = &conn->request; + if (req->proxy) { + hio_write_upstream(conn->io, buf, readbytes); + } + return 0; +} + +static int on_request(http_conn_t* conn) { + // NOTE: just reply 403, please refer to examples/tinyhttpd if you want to reply other. + http_msg_t* req = &conn->request; + char buf[256] = {0}; + int len = snprintf(buf, sizeof(buf), "HTTP/%d.%d %d %s\r\nContent-Length: 0\r\n\r\n", + req->major_version, req->minor_version, 403, "Forbidden"); + hio_write(conn->io, buf, len); + return 403; +} + +static void on_close(hio_t* io) { + // printf("on_close fd=%d error=%d\n", hio_fd(io), hio_error(io)); + http_conn_t* conn = (http_conn_t*)hevent_userdata(io); + if (conn) { + HV_FREE(conn); + hevent_set_userdata(io, NULL); + } + hio_close_upstream(io); +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + char* str = (char*)buf; + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + // printf("%.*s", readbytes, str); + http_conn_t* conn = (http_conn_t*)hevent_userdata(io); + http_msg_t* req = &conn->request; + switch (conn->state) { + case s_begin: + // printf("s_begin"); + conn->state = s_first_line; + case s_first_line: + // printf("s_first_line\n"); + if (readbytes < 2) { + fprintf(stderr, "Not match \r\n!"); + hio_close(io); + return; + } + str[readbytes - 2] = '\0'; + if (parse_http_request_line(conn, str, readbytes - 2) == false) { + fprintf(stderr, "Failed to parse http request line:\n%s\n", str); + hio_close(io); + return; + } + // start read head + conn->state = s_head; + hio_readline(io); + break; + case s_head: + // printf("s_head\n"); + if (readbytes < 2) { + fprintf(stderr, "Not match \r\n!"); + hio_close(io); + return; + } + if (readbytes == 2 && str[0] == '\r' && str[1] == '\n') { + conn->state = s_head_end; + } else { + // NOTE: save head + if (strnicmp(str, "Proxy-", 6) != 0) { + if (req->head_len + readbytes < HTTP_MAX_HEAD_LENGTH) { + memcpy(req->head + req->head_len, buf, readbytes); + req->head_len += readbytes; + } + } + str[readbytes - 2] = '\0'; + if (parse_http_head(conn, str, readbytes - 2) == false) { + fprintf(stderr, "Failed to parse http head:\n%s\n", str); + hio_close(io); + return; + } + hio_readline(io); + break; + } + case s_head_end: + // printf("s_head_end\n"); + if (on_head_end(conn) < 0) { + hio_close(io); + return; + } + if (req->content_length == 0) { + conn->state = s_end; + if (req->proxy) { + // NOTE: wait upstream connect! + } else { + goto s_end; + } + } else { + conn->state = s_body; + if (req->proxy) { + // NOTE: start read body on_upstream_connect + // hio_read_start(io); + } else { + // WARN: too large content_length should read multiple times! + hio_readbytes(io, req->content_length); + } + break; + } + case s_body: + // printf("s_body\n"); + if (on_body(conn, buf, readbytes) < 0) { + hio_close(io); + return; + } + req->body = str; + req->body_len += readbytes; + if (readbytes == req->content_length) { + conn->state = s_end; + } else { + // Not end + break; + } + case s_end: +s_end: + // printf("s_end\n"); + // received complete request + if (req->proxy) { + // NOTE: reply by upstream + } else { + on_request(conn); + } + if (hio_is_closed(io)) return; + if (req->keepalive) { + // Connection: keep-alive\r\n + // reset and receive next request + memset(&conn->request, 0, sizeof(http_msg_t)); + // memset(&conn->response, 0, sizeof(http_msg_t)); + conn->state = s_first_line; + hio_readline(io); + } else { + // Connection: close\r\n + if (req->proxy) { + // NOTE: wait upstream close! + } else { + hio_close(io); + } + } + break; + default: break; + } +} + +static void new_conn_event(hevent_t* ev) { + hloop_t* loop = ev->loop; + hio_t* io = (hio_t*)hevent_userdata(ev); + hio_attach(loop, io); + + /* + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("tid=%ld connfd=%d [%s] <= [%s]\n", + (long)hv_gettid(), + (int)hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_set_keepalive_timeout(io, HTTP_KEEPALIVE_TIMEOUT); + + http_conn_t* conn = NULL; + HV_ALLOC_SIZEOF(conn); + conn->io = io; + hevent_set_userdata(io, conn); + // start read first line + conn->state = s_first_line; + hio_readline(io); +} + +static hloop_t* get_next_loop() { + static int s_cur_index = 0; + if (s_cur_index == thread_num) { + s_cur_index = 0; + } + return worker_loops[s_cur_index++]; +} + +static void on_accept(hio_t* io) { + hio_detach(io); + + hloop_t* worker_loop = get_next_loop(); + hevent_t ev; + memset(&ev, 0, sizeof(ev)); + ev.loop = worker_loop; + ev.cb = new_conn_event; + ev.userdata = io; + hloop_post_event(worker_loop, &ev); +} + +static HTHREAD_ROUTINE(worker_thread) { + hloop_t* loop = (hloop_t*)userdata; + hloop_run(loop); + return 0; +} + +static HTHREAD_ROUTINE(accept_thread) { + hloop_t* loop = (hloop_t*)userdata; + hio_t* listenio = hloop_create_tcp_server(loop, proxy_host, proxy_port, on_accept); + if (listenio == NULL) { + exit(1); + } + if (proxy_ssl) { + hio_enable_ssl(listenio); + } + printf("tinyproxyd listening on %s:%d, listenfd=%d, thread_num=%d\n", + proxy_host, proxy_port, hio_fd(listenio), thread_num); + hloop_run(loop); + return 0; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s proxy_port [thread_num]\n", argv[0]); + return -10; + } + proxy_port = atoi(argv[1]); + if (argc > 2) { + thread_num = atoi(argv[2]); + } else { + thread_num = get_ncpu(); + } + if (thread_num == 0) thread_num = 1; + + worker_loops = (hloop_t**)malloc(sizeof(hloop_t*) * thread_num); + for (int i = 0; i < thread_num; ++i) { + worker_loops[i] = hloop_new(HLOOP_FLAG_AUTO_FREE); + hthread_create(worker_thread, worker_loops[i]); + } + + accept_loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + accept_thread(accept_loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/udp_echo_server.c b/external/libhv/libhv-1.3.2/examples/udp_echo_server.c new file mode 100644 index 0000000..5ca0b13 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/udp_echo_server.c @@ -0,0 +1,73 @@ +/* + * udp echo server + * + * @build make examples + * @server bin/udp_echo_server 1234 + * @client bin/nc -u 127.0.0.1 1234 + * nc -u 127.0.0.1 1234 + * + */ + +#include "hloop.h" +#include "hsocket.h" + +/* + * @test kcp_server + * #define TEST_KCP 1 + * + * @build ./configure --with-kcp && make clean && make + * @server bin/udp_echo_server 1234 + * @client bin/nc -k 127.0.0.1 1234 + * + */ +#define TEST_KCP 0 + +static void on_recvfrom(hio_t* io, void* buf, int readbytes) { + printf("on_recvfrom fd=%d readbytes=%d\n", hio_fd(io), readbytes); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("[%s] <=> [%s]\n", + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + + char* str = (char*)buf; + printf("< %.*s", readbytes, str); + // echo + printf("> %.*s", readbytes, str); + hio_write(io, buf, readbytes); + +#if TEST_KCP + if (strncmp(str, "CLOSE", 5) == 0) { + hio_close_rudp(io, hio_peeraddr(io)); + } +#endif +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port|path\n", argv[0]); + return -10; + } + const char* host = "0.0.0.0"; + int port = atoi(argv[1]); +#if ENABLE_UDS + if (port == 0) { + host = argv[1]; + port = -1; + } +#endif + + hloop_t* loop = hloop_new(0); + hio_t* io = hloop_create_udp_server(loop, host, port); + if (io == NULL) { + return -20; + } +#if TEST_KCP + hio_set_kcp(io, NULL); +#endif + hio_setcb_read(io, on_recvfrom); + hio_read(io); + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/udp_proxy_server.c b/external/libhv/libhv-1.3.2/examples/udp_proxy_server.c new file mode 100644 index 0000000..62163ee --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/udp_proxy_server.c @@ -0,0 +1,53 @@ +/* + * udp proxy server + * + * @build: make examples + * @udp_server: bin/udp_echo_server 1234 + * @proxy_server: bin/udp_proxy_server 2222 127.0.0.1:1234 + * @client: bin/nc -u 127.0.0.1 2222 + * > hello + * < hello + */ + +#include "hloop.h" + +static char proxy_host[64] = "0.0.0.0"; +static int proxy_port = 1080; + +static char backend_host[64] = "127.0.0.1"; +static int backend_port = 80; + +// hloop_create_udp_server -> hio_setup_udp_upstream + +int main(int argc, char** argv) { + if (argc < 3) { + printf("Usage: %s proxy_port backend_host:backend_port\n", argv[0]); + return -10; + } + proxy_port = atoi(argv[1]); + char* pos = strchr(argv[2], ':'); + if (pos) { + int len = pos - argv[2]; + if (len > 0) { + memcpy(backend_host, argv[2], len); + backend_host[len] = '\0'; + } + backend_port = atoi(pos + 1); + } else { + strncpy(backend_host, argv[2], sizeof(backend_host)); + } + printf("%s:%d proxy %s:%d\n", proxy_host, proxy_port, backend_host, backend_port); + + hloop_t* loop = hloop_new(0); + hio_t* io = hloop_create_udp_server(loop, proxy_host, proxy_port); + if (io == NULL) { + return -20; + } + hio_t* upstream_io = hio_setup_udp_upstream(io, backend_host, backend_port); + if (upstream_io == NULL) { + return -30; + } + hloop_run(loop); + hloop_free(&loop); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/websocket_client_test.cpp b/external/libhv/libhv-1.3.2/examples/websocket_client_test.cpp new file mode 100644 index 0000000..42a7f7c --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/websocket_client_test.cpp @@ -0,0 +1,118 @@ +/* + * websocket client + * + * @build make examples + * @server bin/websocket_server_test 8888 + * @client bin/websocket_client_test ws://127.0.0.1:8888/test + * @clients bin/websocket_client_test ws://127.0.0.1:8888/test 100 + * @python scripts/websocket_server.py + * @js html/websocket_client.html + * + */ + +#include "WebSocketClient.h" + +using namespace hv; + +class MyWebSocketClient : public WebSocketClient { +public: + MyWebSocketClient(EventLoopPtr loop = NULL) : WebSocketClient(loop) {} + ~MyWebSocketClient() {} + + int connect(const char* url) { + // set callbacks + onopen = [this]() { + const HttpResponsePtr& resp = getHttpResponse(); + printf("onopen\n%s\n", resp->body.c_str()); + // printf("response:\n%s\n", resp->Dump(true, true).c_str()); + }; + onmessage = [this](const std::string& msg) { + printf("onmessage(type=%s len=%d): %.*s\n", opcode() == WS_OPCODE_TEXT ? "text" : "binary", + (int)msg.size(), (int)msg.size(), msg.data()); + }; + onclose = []() { + printf("onclose\n"); + }; + + // ping + setPingInterval(10000); + + // reconnect: 1,2,4,8,10,10,10... + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = 1000; + reconn.max_delay = 10000; + reconn.delay_policy = 2; + setReconnect(&reconn); + + /* + auto req = std::make_shared(); + req->method = HTTP_POST; + req->headers["Origin"] = "http://example.com"; + req->json["app_id"] = "123456"; + req->json["app_secret"] = "abcdefg"; + printf("request:\n%s\n", req->Dump(true, true).c_str()); + setHttpRequest(req); + */ + + http_headers headers; + headers["Origin"] = "http://example.com/"; + return open(url, headers); + }; +}; +typedef std::shared_ptr MyWebSocketClientPtr; + +int TestMultiClientsRunInOneEventLoop(const char* url, int nclients) { + auto loop_thread = std::make_shared(); + loop_thread->start(); + + std::map clients; + for (int i = 0; i < nclients; ++i) { + MyWebSocketClient* client = new MyWebSocketClient(loop_thread->loop()); + client->connect(url); + clients[i] = MyWebSocketClientPtr(client); + } + + // press Enter to stop + while (getchar() != '\n'); + loop_thread->stop(); + loop_thread->join(); + + return 0; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s url\n", argv[0]); + return -10; + } + const char* url = argv[1]; + + int nclients = 0; + if (argc > 2) { + nclients = atoi(argv[2]); + } + if (nclients > 0) { + return TestMultiClientsRunInOneEventLoop(url, nclients); + } + + MyWebSocketClient ws; + ws.connect(url); + + std::string str; + while (std::getline(std::cin, str)) { + if (str == "close") { + ws.close(); + } else if (str == "open") { + ws.connect(url); + } else if (str == "stop") { + ws.stop(); + break; + } else { + if (!ws.isConnected()) break; + ws.send(str); + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/websocket_server_test.cpp b/external/libhv/libhv-1.3.2/examples/websocket_server_test.cpp new file mode 100644 index 0000000..ee290d1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/websocket_server_test.cpp @@ -0,0 +1,115 @@ +/* + * websocket server + * + * @build make examples + * @server bin/websocket_server_test 9999 + * @client bin/websocket_client_test ws://127.0.0.1:9999/ + * @python scripts/websocket_server.py + * @js html/websocket_client.html + * + */ + +#include "WebSocketServer.h" +#include "EventLoop.h" +#include "htime.h" + +using namespace hv; + +/* + * #define TEST_WSS 1 + * + * @build ./configure --with-openssl && make clean && make + * + * @server bin/websocket_server_test 9999 + * + * @client bin/websocket_client_test ws://127.0.0.1:9999/ + * bin/websocket_client_test wss://127.0.0.1:10000/ + * + */ +#define TEST_WSS 0 + +using namespace hv; + +class MyContext { +public: + MyContext() { + printf("MyContext::MyContext()\n"); + timerID = INVALID_TIMER_ID; + } + ~MyContext() { + printf("MyContext::~MyContext()\n"); + } + + int handleMessage(const std::string& msg, enum ws_opcode opcode) { + printf("onmessage(type=%s len=%d): %.*s\n", opcode == WS_OPCODE_TEXT ? "text" : "binary", + (int)msg.size(), (int)msg.size(), msg.data()); + return msg.size(); + } + + TimerID timerID; +}; + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s port\n", argv[0]); + return -10; + } + int port = atoi(argv[1]); + + HttpService http; + http.GET("/ping", [](const HttpContextPtr& ctx) { + return ctx->send("pong"); + }); + + WebSocketService ws; + // ws.setPingInterval(10000); + ws.onopen = [](const WebSocketChannelPtr& channel, const HttpRequestPtr& req) { + printf("onopen: GET %s\n", req->Path().c_str()); + auto ctx = channel->newContextPtr(); + // send(time) every 1s + ctx->timerID = setInterval(1000, [channel](TimerID id) { + if (channel->isConnected() && channel->isWriteComplete()) { + char str[DATETIME_FMT_BUFLEN] = {0}; + datetime_t dt = datetime_now(); + datetime_fmt(&dt, str); + channel->send(str); + } + }); + }; + ws.onmessage = [](const WebSocketChannelPtr& channel, const std::string& msg) { + auto ctx = channel->getContextPtr(); + ctx->handleMessage(msg, channel->opcode); + }; + ws.onclose = [](const WebSocketChannelPtr& channel) { + printf("onclose\n"); + auto ctx = channel->getContextPtr(); + if (ctx->timerID != INVALID_TIMER_ID) { + killTimer(ctx->timerID); + ctx->timerID = INVALID_TIMER_ID; + } + // channel->deleteContextPtr(); + }; + + WebSocketServer server; + server.port = port; +#if TEST_WSS + server.https_port = port + 1; + hssl_ctx_opt_t param; + memset(¶m, 0, sizeof(param)); + param.crt_file = "cert/server.crt"; + param.key_file = "cert/server.key"; + param.endpoint = HSSL_SERVER; + if (server.newSslCtx(¶m) != 0) { + fprintf(stderr, "new SSL_CTX failed!\n"); + return -20; + } +#endif + server.registerHttpService(&http); + server.registerWebSocketService(&ws); + + server.start(); + + // press Enter to stop + while (getchar() != '\n'); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/wget.cpp b/external/libhv/libhv-1.3.2/examples/wget.cpp new file mode 100644 index 0000000..1ba52bb --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/wget.cpp @@ -0,0 +1,173 @@ +/* + * @build: make examples + * @server bin/httpd -s restart -d + * @client bin/wget http://127.0.0.1:8080/ + */ + +#include "HttpClient.h" +#include "htime.h" +using namespace hv; + +typedef std::function wget_progress_cb; + +static int wget(const char* url, const char* filepath, wget_progress_cb progress_cb = NULL, bool use_range = true) { + int ret = 0; + HttpClient cli; + HttpRequest req; + HttpResponse resp; + + // HEAD + req.method = HTTP_HEAD; + req.url = url; + ret = cli.send(&req, &resp); + if (ret != 0) { + fprintf(stderr, "request error: %d\n", ret); + return ret; + } + printd("%s", resp.Dump(true, false).c_str()); + if (resp.status_code == HTTP_STATUS_NOT_FOUND) { + fprintf(stderr, "404 Not Found\n"); + return 404; + } + + // use Range? + int range_bytes = 1 << 20; // 1M + long from = 0, to = 0; + size_t content_length = hv::from_string(resp.GetHeader("Content-Length")); + if (use_range) { + use_range = false; + std::string accept_ranges = resp.GetHeader("Accept-Ranges"); + // use Range if server accept_ranges and content_length > 1M + if (resp.status_code == 200 && + accept_ranges == "bytes" && + content_length > range_bytes) { + use_range = true; + } + } + + // open file + std::string filepath_download(filepath); + filepath_download += ".download"; + HFile file; + if (use_range) { + ret = file.open(filepath_download.c_str(), "ab"); + from = file.size(); + } else { + ret = file.open(filepath_download.c_str(), "wb"); + } + if (ret != 0) { + fprintf(stderr, "Failed to open file %s\n", filepath_download.c_str()); + return ret; + } + printf("Save file to %s ...\n", filepath); + + // GET + req.method = HTTP_GET; + req.timeout = 3600; // 1h + if (!use_range) { + size_t received_bytes = 0; + req.http_cb = [&file, &content_length, &received_bytes, &progress_cb] + (HttpMessage* resp, http_parser_state state, const char* data, size_t size) { + if (!resp->headers["Location"].empty()) return; + if (state == HP_HEADERS_COMPLETE) { + content_length = hv::from_string(resp->GetHeader("Content-Length")); + printd("%s", resp->Dump(true, false).c_str()); + } else if (state == HP_BODY) { + if (data && size) { + file.write(data, size); + received_bytes += size; + + if (progress_cb) { + progress_cb(received_bytes, content_length); + } + } + } + }; + ret = cli.send(&req, &resp); + if (ret != 0) { + fprintf(stderr, "request error: %d\n", ret); + goto error; + } + goto success; + } + + // Range: bytes=from-to + while (from < content_length) { + to = from + range_bytes - 1; + if (to >= content_length) to = content_length - 1; + req.SetRange(from, to); + printd("%s", req.Dump(true, false).c_str()); + ret = cli.send(&req, &resp); + if (ret != 0) { + fprintf(stderr, "request error: %d\n", ret); + goto error; + } + printd("%s", resp.Dump(true, false).c_str()); + file.write(resp.body.data(), resp.body.size()); + // fix: resp.body.size != range_bytes on some server + // from = to + 1; + from += resp.body.size(); + + if (progress_cb) { + progress_cb(from, content_length); + } + } + +success: + file.close(); + ret = file.rename(filepath); + if (ret != 0) { + fprintf(stderr, "mv %s => %s failed: %s:%d\n", filepath_download.c_str(), filepath, strerror(ret), ret); + } + return ret; +error: + file.close(); + // file.remove(); + return ret; +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: %s [--use_range] url [filepath]\n", argv[0]); + return -10; + } + int idx = 1; + bool use_range = false; + if (strcmp(argv[idx], "--use_range") == 0) { + use_range = true; + ++idx; + } + const char* url = argv[idx++]; + const char* filepath = "index.html"; + if (argv[idx]) { + filepath = argv[idx]; + } else { + const char* path = strrchr(url, '/'); + if (path && path[1]) { + filepath = path + 1; + } + } + + unsigned int start_time = gettick_ms(); + int last_progress = 0; + wget(url, filepath, [&last_progress](size_t received_bytes, size_t total_bytes) { + // print progress + if (total_bytes == 0) { + printf("\rprogress: %lu/? = ?", (unsigned long)received_bytes); + } else { + int cur_progress = received_bytes * 100 / total_bytes; + if (cur_progress > last_progress) { + printf("\rprogress: %lu/%lu = %d%%", (unsigned long)received_bytes, (unsigned long)total_bytes, (int)cur_progress); + last_progress = cur_progress; + } + } + fflush(stdout); + }, use_range); + unsigned int end_time = gettick_ms(); + unsigned int cost_time = end_time - start_time; + printf("\ncost time %u ms\n", cost_time); + // 1B/ms = 1KB/s = 8Kbps + printf("download rate = %lu KB/s\n", (unsigned long)hv_filesize(filepath) / cost_time); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/examples/wrk.cpp b/external/libhv/libhv-1.3.2/examples/wrk.cpp new file mode 100644 index 0000000..570f1dd --- /dev/null +++ b/external/libhv/libhv-1.3.2/examples/wrk.cpp @@ -0,0 +1,275 @@ +/* + * @build: make examples + * @server bin/httpd -s restart -d + * @client bin/curl -v http://127.0.0.1:8080/ + * @usage: bin/wrk -c 1000 -d 10 -t 4 http://127.0.0.1:8080/ + * + */ + +#include "hv.h" +#include "hmain.h" // import parse_opt +#include "hloop.h" + +#include "EventLoopThreadPool.h" +#include "HttpMessage.h" +#include "HttpParser.h" +using namespace hv; + +static const char options[] = "hvc:d:t:"; + +static const char detail_options[] = R"( + -h Print help infomation + -v Show verbose infomation + -c Number of connections, default: 1000 + -d Duration of test, default: 10s + -t Number of threads, default: 4 +)"; + +static int connections = 1000; +static int duration = 10; +static int threads = 4; + +static bool verbose = false; +static const char* url = NULL; +static bool https = false; +static char ip[64] = "127.0.0.1"; +static int port = 80; + +static bool stop = false; + +static HttpRequestPtr request; +static std::string request_msg; + +typedef struct connection_s { + hio_t* io; + HttpParserPtr parser; + HttpResponsePtr response; + uint64_t request_cnt; + uint64_t response_cnt; + uint64_t ok_cnt; + uint64_t readbytes; + + connection_s() + : parser(HttpParser::New(HTTP_CLIENT, HTTP_V1)) + , response(std::make_shared()) + , request_cnt(0) + , response_cnt(0) + , ok_cnt(0) + , readbytes(0) + { + response->http_cb = [](HttpMessage* res, http_parser_state state, const char* data, size_t size) { + // wrk no need to save data to body + }; + } + + void SendRequest() { + hio_write(io, request_msg.data(), request_msg.size()); + ++request_cnt; + parser->InitResponse(response.get()); + } + + bool RecvResponse(const char* data, int size) { + readbytes += size; + int nparse = parser->FeedRecvData(data, size); + if (nparse != size) { + fprintf(stderr, "http parse error!\n"); + hio_close(io); + return false; + } + if (parser->IsComplete()) { + ++response_cnt; + if (response->status_code == HTTP_STATUS_OK) { + ++ok_cnt; + } + return true; + } + return false; + } +} connection_t; +static connection_t** conns = NULL; + +static std::atomic connected_num(0); +static std::atomic disconnected_num(0); + +static void print_help() { + printf("Usage: wrk [%s] \n", options); + printf("Options:\n%s\n", detail_options); +} + +static void print_cmd() { + printf("Running %ds test @ %s\n", duration, url); + printf("%d threads and %d connections\n", threads, connections); +} + +static void print_result() { + uint64_t total_request_cnt = 0; + uint64_t total_response_cnt = 0; + uint64_t total_ok_cnt = 0; + uint64_t total_readbytes = 0; + connection_t* conn = NULL; + for (int i = 0; i < connections; ++i) { + conn = conns[i]; + total_request_cnt += conn->request_cnt; + total_response_cnt += conn->response_cnt; + total_ok_cnt += conn->ok_cnt; + total_readbytes += conn->readbytes; + } + printf("%llu requests, %llu OK, %lluMB read in %ds\n", + LLU(total_request_cnt), + LLU(total_ok_cnt), + LLU(total_readbytes >> 20), + duration); + printf("Requests/sec: %8llu\n", LLU(total_response_cnt / duration)); + printf("Transfer/sec: %8lluMB\n", LLU((total_readbytes / duration) >> 20)); +} + +static void start_reconnect(hio_t* io); +static void on_close(hio_t* io) { + if (++disconnected_num == connections) { + if (verbose) { + printf("all disconnected\n"); + } + } + + if (!stop) { + // NOTE: nginx keepalive_requests = 100 + start_reconnect(io); + } +} + +static void on_recv(hio_t* io, void* buf, int readbytes) { + connection_t* conn = (connection_t*)hevent_userdata(io); + if (conn->RecvResponse((const char*)buf, readbytes)) { + conn->SendRequest(); + } +} + +static void on_connect(hio_t* io) { + if (++connected_num == connections) { + if (verbose) { + printf("all connected\n"); + } + } + + connection_t* conn = (connection_t*)hevent_userdata(io); + conn->SendRequest(); + + hio_setcb_read(io, on_recv); + hio_read(io); +} + +static void start_connect(hloop_t* loop, connection_t* conn) { + hio_t* io = hio_create_socket(loop, ip, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (io == NULL) { + perror("socket"); + exit(1); + } + conn->io = io; + hevent_set_userdata(io, conn); + if (https) { + hio_enable_ssl(io); + } + tcp_nodelay(hio_fd(io), 1); + hio_setcb_connect(io, on_connect); + hio_setcb_close(io, on_close); + hio_connect(io); +} + +static void start_reconnect(hio_t* io) { + hloop_t* loop = hevent_loop(io); + connection_t* conn = (connection_t*)hevent_userdata(io); + start_connect(loop, conn); +} + +int main(int argc, char** argv) { + // parse cmdline + main_ctx_init(argc, argv); + int ret = parse_opt(argc, argv, options); + if (ret != 0) { + print_help(); + exit(ret); + } + + if (get_arg("h") || g_main_ctx.arg_list_size != 1) { + print_help(); + exit(0); + } + url = g_main_ctx.arg_list[0]; + + if (get_arg("v")) { + verbose = true; + } + + const char* strConnections = get_arg("c"); + const char* strDuration = get_arg("d"); + const char* strThreads = get_arg("t"); + + if (strConnections) connections = atoi(strConnections); + if (strDuration) duration = atoi(strDuration); + if (strThreads) threads = atoi(strThreads); + + print_cmd(); + + // ParseUrl + request = std::make_shared(); + request->url = url; + request->ParseUrl(); + https = request->scheme == "https"; + const char* host = request->host.c_str(); + port = request->port; + + // ResolveAddr + if (is_ipaddr(host)) { + strcpy(ip, host); + } else { + sockaddr_u addr; + if (ResolveAddr(host, &addr) != 0) { + fprintf(stderr, "Could not resolve host: %s\n", host); + exit(1); + } + sockaddr_ip(&addr, ip, sizeof(ip)); + } + + // Test connect + printf("Connect to %s:%d ...\n", ip, port); + int connfd = ConnectTimeout(ip, port); + if (connfd < 0) { + fprintf(stderr, "Could not connect to %s:%d\n", ip, port); + exit(1); + } else { + closesocket(connfd); + } + + // Dump request + request->headers["User-Agent"] = std::string("libhv/") + hv_version(); + request->headers["Connection"] = "keep-alive"; + request_msg = request->Dump(true, true); + printf("%s", request_msg.c_str()); + + // EventLoopThreadPool + EventLoopThreadPool loop_threads(threads); + loop_threads.start(true); + + // connections + conns = (connection_t**)malloc(sizeof(connection_t*) * connections); + for (int i = 0; i < connections; ++i) { + conns[i] = new connection_t; + + EventLoopPtr loop = loop_threads.nextLoop(); + hloop_t* hloop = loop->loop(); + loop->runInLoop(std::bind(start_connect, loop->loop(), conns[i])); + } + + // stop after duration + loop_threads.loop()->setTimeout(duration * 1000, [&loop_threads](TimerID timerID){ + stop = true; + loop_threads.stop(false); + }); + + // wait loop_threads exit + loop_threads.join(); + + print_result(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/getting_started.sh b/external/libhv/libhv-1.3.2/getting_started.sh new file mode 100755 index 0000000..a17767f --- /dev/null +++ b/external/libhv/libhv-1.3.2/getting_started.sh @@ -0,0 +1,93 @@ +#!/bin/bash + +echo "Welcome to libhv!" +echo "Press any key to run ..." + +echo_cmd() { + echo -e "\n\033[36m$cmd\033[0m" + read -n1 +} + +run_cmd() { + echo_cmd + $cmd +} + +# compile httpd curl +if [ ! -x bin/httpd -o ! -x bin/curl ]; then + cmd="make httpd curl" && echo_cmd + ./configure + make clean + make -j4 httpd curl +fi + +# run httpd +processes=$(ps aux | grep -v grep | grep httpd | wc -l) +if [ $processes -lt 1 ]; then + cmd="bin/httpd -c etc/httpd.conf -s restart -d" && run_cmd +fi +ps aux | grep -v grep | grep httpd + +# http file service +cmd="bin/curl -v localhost:8080" && run_cmd + +# http indexof service +cmd="bin/curl -v localhost:8080/downloads/" && run_cmd +cmd="bin/curl -v localhost:8080/downloads/中文.html" && run_cmd + +# http api service +cmd="bin/curl -v localhost:8080/paths" && run_cmd + +cmd="bin/curl -v localhost:8080/ping" && run_cmd + +cmd="bin/curl -v localhost:8080/data" && run_cmd + +cmd="bin/curl -v localhost:8080/html/index.html" && run_cmd + +cmd="bin/curl -v localhost:8080/get?env=1" && run_cmd + +cmd="bin/curl -v localhost:8080/service" && run_cmd + +cmd="bin/curl -v localhost:8080/async" && run_cmd + +cmd="bin/curl -v localhost:8080/wildcard/test" && run_cmd + +cmd="bin/curl -v localhost:8080/echo -d 'hello,world!'" && echo_cmd +bin/curl -v localhost:8080/echo -d 'hello,world!' + +cmd="bin/curl -v localhost:8080/query?page_no=1&page_size=10" && run_cmd + +cmd="bin/curl -v localhost:8080/kv -H 'Content-Type:application/x-www-form-urlencoded' -d 'user=admin&pswd=123456'" && echo_cmd + bin/curl -v localhost:8080/kv -H 'Content-Type:application/x-www-form-urlencoded' -d 'user=admin&pswd=123456' + +cmd="bin/curl -v localhost:8080/json -H 'Content-Type:application/json' -d '{\"user\":\"admin\",\"pswd\":\"123456\"}'" && echo_cmd + bin/curl -v localhost:8080/json -H 'Content-Type:application/json' -d '{"user":"admin","pswd":"123456"}' + +cmd="bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456'" && echo_cmd + bin/curl -v localhost:8080/form -F 'user=admin' -F 'pswd=123456' + +cmd="bin/curl -v localhost:8080/upload?filename=LICENSE -d '@LICENSE'" && echo_cmd + bin/curl -v localhost:8080/upload?filename=LICENSE -d '@LICENSE' + +cmd="bin/curl -v localhost:8080/upload -F 'file=@LICENSE'" && echo_cmd + bin/curl -v localhost:8080/upload -F 'file=@LICENSE' + +cmd="bin/curl -v localhost:8080/upload/README.md -d '@README.md'" && echo_cmd + bin/curl -v localhost:8080/upload/README.md -d '@README.md' + +cmd="bin/curl -v localhost:8080/test -H 'Content-Type:application/x-www-form-urlencoded' -d 'bool=1&int=123&float=3.14&string=hello'" && echo_cmd + bin/curl -v localhost:8080/test -H 'Content-Type:application/x-www-form-urlencoded' -d 'bool=1&int=123&float=3.14&string=hello' + +cmd="bin/curl -v localhost:8080/test -H 'Content-Type:application/json' -d '{\"bool\":true,\"int\":123,\"float\":3.14,\"string\":\"hello\"}'" && echo_cmd + bin/curl -v localhost:8080/test -H 'Content-Type:application/json' -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' + +cmd="bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello'" && echo_cmd + bin/curl -v localhost:8080/test -F 'bool=1' -F 'int=123' -F 'float=3.14' -F 'string=hello' + +# RESTful API: /group/:group_name/user/:user_id +cmd="bin/curl -v -X DELETE localhost:8080/group/test/user/123" && run_cmd + +# show log +cmd="tail -n 50 logs/httpd*.log" && run_cmd + +echo -e "\nEnjoy libhv!\n" diff --git a/external/libhv/libhv-1.3.2/hconfig.h.in b/external/libhv/libhv-1.3.2/hconfig.h.in new file mode 100644 index 0000000..700f9e7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/hconfig.h.in @@ -0,0 +1,102 @@ +#ifndef HV_CONFIG_H_ +#define HV_CONFIG_H_ + +#ifndef HAVE_STDBOOL_H +#define HAVE_STDBOOL_H @HAVE_STDBOOL_H@ +#endif + +#ifndef HAVE_STDINT_H +#define HAVE_STDINT_H @HAVE_STDINT_H@ +#endif + +#ifndef HAVE_STDATOMIC_H +#define HAVE_STDATOMIC_H @HAVE_STDATOMIC_H@ +#endif + +#ifndef HAVE_SYS_TYPES_H +#define HAVE_SYS_TYPES_H @HAVE_SYS_TYPES_H@ +#endif + +#ifndef HAVE_SYS_STAT_H +#define HAVE_SYS_STAT_H @HAVE_SYS_STAT_H@ +#endif + +#ifndef HAVE_SYS_TIME_H +#define HAVE_SYS_TIME_H @HAVE_SYS_TIME_H@ +#endif + +#ifndef HAVE_FCNTL_H +#define HAVE_FCNTL_H @HAVE_FCNTL_H@ +#endif + +#ifndef HAVE_PTHREAD_H +#define HAVE_PTHREAD_H @HAVE_PTHREAD_H@ +#endif + +#ifndef HAVE_ENDIAN_H +#define HAVE_ENDIAN_H @HAVE_ENDIAN_H@ +#endif + +#ifndef HAVE_SYS_ENDIAN_H +#define HAVE_SYS_ENDIAN_H @HAVE_SYS_ENDIAN_H@ +#endif + +#ifndef HAVE_GETTID +#define HAVE_GETTID @HAVE_GETTID@ +#endif + +#ifndef HAVE_STRLCPY +#define HAVE_STRLCPY @HAVE_STRLCPY@ +#endif + +#ifndef HAVE_STRLCAT +#define HAVE_STRLCAT @HAVE_STRLCAT@ +#endif + +#ifndef HAVE_CLOCK_GETTIME +#define HAVE_CLOCK_GETTIME @HAVE_CLOCK_GETTIME@ +#endif + +#ifndef HAVE_GETTIMEOFDAY +#define HAVE_GETTIMEOFDAY @HAVE_GETTIMEOFDAY@ +#endif + +#ifndef HAVE_PTHREAD_SPIN_LOCK +#define HAVE_PTHREAD_SPIN_LOCK @HAVE_PTHREAD_SPIN_LOCK@ +#endif + +#ifndef HAVE_PTHREAD_MUTEX_TIMEDLOCK +#define HAVE_PTHREAD_MUTEX_TIMEDLOCK @HAVE_PTHREAD_MUTEX_TIMEDLOCK@ +#endif + +#ifndef HAVE_SEM_TIMEDWAIT +#define HAVE_SEM_TIMEDWAIT @HAVE_SEM_TIMEDWAIT@ +#endif + +#ifndef HAVE_PIPE +#define HAVE_PIPE @HAVE_PIPE@ +#endif + +#ifndef HAVE_SOCKETPAIR +#define HAVE_SOCKETPAIR @HAVE_SOCKETPAIR@ +#endif + +#ifndef HAVE_EVENTFD +#define HAVE_EVENTFD @HAVE_EVENTFD@ +#endif + +#ifndef HAVE_SETPROCTITLE +#define HAVE_SETPROCTITLE @HAVE_SETPROCTITLE@ +#endif + +#cmakedefine WITH_OPENSSL 1 +#cmakedefine WITH_GNUTLS 1 +#cmakedefine WITH_MBEDTLS 1 + +#cmakedefine ENABLE_UDS 1 +#cmakedefine USE_MULTIMAP 1 + +#cmakedefine WITH_WEPOLL 1 +#cmakedefine WITH_KCP 1 + +#endif // HV_CONFIG_H_ diff --git a/external/libhv/libhv-1.3.2/hexport.h b/external/libhv/libhv-1.3.2/hexport.h new file mode 100644 index 0000000..7d37016 --- /dev/null +++ b/external/libhv/libhv-1.3.2/hexport.h @@ -0,0 +1,157 @@ +#ifndef HV_EXPORT_H_ +#define HV_EXPORT_H_ + +// HV_EXPORT +#if defined(HV_STATICLIB) || defined(HV_SOURCE) + #define HV_EXPORT +#elif defined(_MSC_VER) + #if defined(HV_DYNAMICLIB) || defined(HV_EXPORTS) || defined(hv_EXPORTS) + #define HV_EXPORT __declspec(dllexport) + #else + #define HV_EXPORT __declspec(dllimport) + #endif +#elif defined(__GNUC__) + #define HV_EXPORT __attribute__((visibility("default"))) +#else + #define HV_EXPORT +#endif + +// HV_INLINE +#define HV_INLINE static inline + +// HV_DEPRECATED +#if defined(HV_NO_DEPRECATED) +#define HV_DEPRECATED +#elif defined(__GNUC__) || defined(__clang__) +#define HV_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) +#define HV_DEPRECATED __declspec(deprecated) +#else +#define HV_DEPRECATED +#endif + +// HV_UNUSED +#if defined(__GNUC__) + #define HV_UNUSED __attribute__((visibility("unused"))) +#else + #define HV_UNUSED +#endif + +// @param[IN | OUT | INOUT] +#ifndef IN +#define IN +#endif + +#ifndef OUT +#define OUT +#endif + +#ifndef INOUT +#define INOUT +#endif + +// @field[OPTIONAL | REQUIRED | REPEATED] +#ifndef OPTIONAL +#define OPTIONAL +#endif + +#ifndef REQUIRED +#define REQUIRED +#endif + +#ifndef REPEATED +#define REPEATED +#endif + +#ifdef __cplusplus + +#ifndef EXTERN_C +#define EXTERN_C extern "C" +#endif + +#ifndef BEGIN_EXTERN_C +#define BEGIN_EXTERN_C extern "C" { +#endif + +#ifndef END_EXTERN_C +#define END_EXTERN_C } // extern "C" +#endif + +#ifndef BEGIN_NAMESPACE +#define BEGIN_NAMESPACE(ns) namespace ns { +#endif + +#ifndef END_NAMESPACE +#define END_NAMESPACE(ns) } // namespace ns +#endif + +#ifndef USING_NAMESPACE +#define USING_NAMESPACE(ns) using namespace ns; +#endif + +#ifndef DEFAULT +#define DEFAULT(x) = x +#endif + +#ifndef ENUM +#define ENUM(e) enum e +#endif + +#ifndef STRUCT +#define STRUCT(s) struct s +#endif + +#else + +#define EXTERN_C extern +#define BEGIN_EXTERN_C +#define END_EXTERN_C + +#define BEGIN_NAMESPACE(ns) +#define END_NAMESPACE(ns) +#define USING_NAMESPACE(ns) + +#ifndef DEFAULT +#define DEFAULT(x) +#endif + +#ifndef ENUM +#define ENUM(e)\ +typedef enum e e;\ +enum e +#endif + +#ifndef STRUCT +#define STRUCT(s)\ +typedef struct s s;\ +struct s +#endif + +#endif // __cplusplus + +#define BEGIN_NAMESPACE_HV BEGIN_NAMESPACE(hv) +#define END_NAMESPACE_HV END_NAMESPACE(hv) +#define USING_NAMESPACE_HV USING_NAMESPACE(hv) + +// MSVC ports +#ifdef _MSC_VER + +#pragma warning (disable: 4251) // STL dll +#pragma warning (disable: 4275) // dll-interface + +#if _MSC_VER < 1900 // < VS2015 + +#ifndef __cplusplus +#ifndef inline +#define inline __inline +#endif +#endif + +#ifndef snprintf +#define snprintf _snprintf +#endif + +#endif +#endif + +#endif // HV_EXPORT_H_ diff --git a/external/libhv/libhv-1.3.2/html/EventSource.html b/external/libhv/libhv-1.3.2/html/EventSource.html new file mode 100644 index 0000000..f2fec9a --- /dev/null +++ b/external/libhv/libhv-1.3.2/html/EventSource.html @@ -0,0 +1,50 @@ + + + + + +EventSource客户端 + + + + + + URL: + +
+
    +
+
+ + + diff --git a/external/libhv/libhv-1.3.2/html/WebSocket.html b/external/libhv/libhv-1.3.2/html/WebSocket.html new file mode 100644 index 0000000..493be52 --- /dev/null +++ b/external/libhv/libhv-1.3.2/html/WebSocket.html @@ -0,0 +1,53 @@ + + + + + +WebSocket客户端 + + + + + + URL: + +
+
    +
+
+ + + diff --git a/external/libhv/libhv-1.3.2/html/downloads/libhv-vs-nginx.png b/external/libhv/libhv-1.3.2/html/downloads/libhv-vs-nginx.png new file mode 100644 index 0000000..4964f4b Binary files /dev/null and b/external/libhv/libhv-1.3.2/html/downloads/libhv-vs-nginx.png differ diff --git a/external/libhv/libhv-1.3.2/html/downloads/中文.html b/external/libhv/libhv-1.3.2/html/downloads/中文.html new file mode 100644 index 0000000..078a0dd --- /dev/null +++ b/external/libhv/libhv-1.3.2/html/downloads/中文.html @@ -0,0 +1,10 @@ + + + + + 中文测试 + + +

欢迎使用 libhv

+ + diff --git a/external/libhv/libhv-1.3.2/html/error.html b/external/libhv/libhv-1.3.2/html/error.html new file mode 100644 index 0000000..27fe109 --- /dev/null +++ b/external/libhv/libhv-1.3.2/html/error.html @@ -0,0 +1,12 @@ + + + + Error + + +

An error occurred.

+

Sorry, the page you are looking for is currently unavailable.
Please try again later.

+

If you are the system administrator of this resource then you should check the error log for details.

+

Faithfully yours, httpd.

+ + diff --git a/external/libhv/libhv-1.3.2/html/index.html b/external/libhv/libhv-1.3.2/html/index.html new file mode 100644 index 0000000..10b1e5e --- /dev/null +++ b/external/libhv/libhv-1.3.2/html/index.html @@ -0,0 +1,9 @@ + + + + libhv + + +

Welcome to libhv

+ + diff --git a/external/libhv/libhv-1.3.2/http/Http1Parser.cpp b/external/libhv/libhv-1.3.2/http/Http1Parser.cpp new file mode 100644 index 0000000..0975581 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/Http1Parser.cpp @@ -0,0 +1,159 @@ +#include "Http1Parser.h" + +#define MAX_CONTENT_LENGTH (1 << 24) // 16M + +static int on_url(http_parser* parser, const char *at, size_t length); +static int on_status(http_parser* parser, const char *at, size_t length); +static int on_header_field(http_parser* parser, const char *at, size_t length); +static int on_header_value(http_parser* parser, const char *at, size_t length); +static int on_body(http_parser* parser, const char *at, size_t length); +static int on_message_begin(http_parser* parser); +static int on_headers_complete(http_parser* parser); +static int on_message_complete(http_parser* parser); +static int on_chunk_header(http_parser* parser); +static int on_chunk_complete(http_parser* parser); + +http_parser_settings Http1Parser::cbs = { + on_message_begin, + on_url, + on_status, + on_header_field, + on_header_value, + on_headers_complete, + on_body, + on_message_complete, + on_chunk_header, + on_chunk_complete +}; + +Http1Parser::Http1Parser(http_session_type type) { + http_parser_init(&parser, HTTP_BOTH); + parser.data = this; + flags = 0; + state = HP_START_REQ_OR_RES; + submited = NULL; + parsed = NULL; +} + +Http1Parser::~Http1Parser() { +} + +int on_url(http_parser* parser, const char *at, size_t length) { + printd("on_url:%.*s\n", (int)length, at); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_URL; + hp->url.append(at, length); + return 0; +} + +int on_status(http_parser* parser, const char *at, size_t length) { + printd("on_status:%d %.*s\n", (int)parser->status_code, (int)length, at); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_STATUS; + return 0; +} + +int on_header_field(http_parser* parser, const char *at, size_t length) { + printd("on_header_field:%.*s\n", (int)length, at); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->handle_header(); + hp->state = HP_HEADER_FIELD; + hp->header_field.append(at, length); + return 0; +} + +int on_header_value(http_parser* parser, const char *at, size_t length) { + printd("on_header_value:%.*s\n", (int)length, at); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_HEADER_VALUE; + hp->header_value.append(at, length); + return 0; +} + +int on_body(http_parser* parser, const char *at, size_t length) { + printd("on_body:%d\n", (int)length); + // printd("on_body:%.*s\n", (int)length, at); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_BODY; + if (hp->invokeHttpCb(at, length) != 0) { + hp->parsed->body.append(at, length); + } + return 0; +} + +int on_message_begin(http_parser* parser) { + printd("on_message_begin\n"); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_MESSAGE_BEGIN; + hp->invokeHttpCb(); + return 0; +} + +int on_headers_complete(http_parser* parser) { + printd("on_headers_complete\n"); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->handle_header(); + + bool skip_body = false; + hp->parsed->http_major = parser->http_major; + hp->parsed->http_minor = parser->http_minor; + if (hp->parsed->type == HTTP_REQUEST) { + HttpRequest* req = (HttpRequest*)hp->parsed; + req->method = (http_method)parser->method; + req->url = hp->url; + } + else if (hp->parsed->type == HTTP_RESPONSE) { + HttpResponse* res = (HttpResponse*)hp->parsed; + res->status_code = (http_status)parser->status_code; + // response to HEAD + if (hp->flags & F_SKIPBODY) { + skip_body = true; + } + } + + auto iter = hp->parsed->headers.find("content-type"); + if (iter != hp->parsed->headers.end()) { + hp->parsed->content_type = http_content_type_enum(iter->second.c_str()); + } + iter = hp->parsed->headers.find("content-length"); + if (iter != hp->parsed->headers.end()) { + size_t content_length = atoll(iter->second.c_str()); + hp->parsed->content_length = content_length; + size_t reserve_length = MIN(content_length + 1, MAX_CONTENT_LENGTH); + if ((!skip_body) && reserve_length > hp->parsed->body.capacity()) { + hp->parsed->body.reserve(reserve_length); + } + } + hp->state = HP_HEADERS_COMPLETE; + hp->invokeHttpCb(); + return skip_body ? 1 : 0; +} + +int on_message_complete(http_parser* parser) { + printd("on_message_complete\n"); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_MESSAGE_COMPLETE; + hp->invokeHttpCb(); + return 0; +} + +int on_chunk_header(http_parser* parser) { + printd("on_chunk_header:%llu\n", parser->content_length); + Http1Parser* hp = (Http1Parser*)parser->data; + int chunk_size = parser->content_length; + int reserve_size = MIN(chunk_size + 1, MAX_CONTENT_LENGTH); + if (reserve_size > hp->parsed->body.capacity()) { + hp->parsed->body.reserve(reserve_size); + } + hp->state = HP_CHUNK_HEADER; + hp->invokeHttpCb(NULL, chunk_size); + return 0; +} + +int on_chunk_complete(http_parser* parser) { + printd("on_chunk_complete\n"); + Http1Parser* hp = (Http1Parser*)parser->data; + hp->state = HP_CHUNK_COMPLETE; + hp->invokeHttpCb(); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/http/Http1Parser.h b/external/libhv/libhv-1.3.2/http/Http1Parser.h new file mode 100644 index 0000000..9cccdc3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/Http1Parser.h @@ -0,0 +1,135 @@ +#ifndef HV_HTTP1_PARSER_H_ +#define HV_HTTP1_PARSER_H_ + +#include "HttpParser.h" +#include "http_parser.h" + +class Http1Parser : public HttpParser { +public: + static http_parser_settings cbs; + http_parser parser; + int flags; + http_parser_state state; + HttpMessage* submited; + HttpMessage* parsed; + // tmp + std::string url; // for on_url + std::string header_field; // for on_header_field + std::string header_value; // for on_header_value + std::string sendbuf; // for GetSendData + + Http1Parser(http_session_type type = HTTP_CLIENT); + virtual ~Http1Parser(); + + void handle_header() { + if (header_field.size() != 0) { + if (stricmp(header_field.c_str(), "Set-CooKie") == 0 || + stricmp(header_field.c_str(), "Cookie") == 0) { + HttpCookie cookie; + if (cookie.parse(header_value)) { + parsed->cookies.emplace_back(cookie); + } + } + parsed->headers[header_field] = header_value; + header_field.clear(); + header_value.clear(); + } + } + + virtual int GetSendData(char** data, size_t* len) { + if (!submited) { + *data = NULL; + *len = 0; + return 0; + } + sendbuf = submited->Dump(true, true); + submited = NULL; + *data = (char*)sendbuf.data(); + *len = sendbuf.size(); + return sendbuf.size(); + } + + virtual int FeedRecvData(const char* data, size_t len) { + return http_parser_execute(&parser, &cbs, data, len); + } + + virtual int GetState() { + return (int)state; + } + + virtual bool WantRecv() { + return state != HP_MESSAGE_COMPLETE; + } + + virtual bool WantSend() { + return state == HP_MESSAGE_COMPLETE; + } + + virtual bool IsComplete() { + return state == HP_MESSAGE_COMPLETE; + } + + virtual bool IsEof() { + FeedRecvData(NULL, 0); + return IsComplete(); + } + + virtual int GetError() { + return parser.http_errno; + } + + virtual const char* StrError(int error) { + return http_errno_description((enum http_errno)error); + } + + // client + // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) + virtual int SubmitRequest(HttpRequest* req) { + submited = req; + if (req) { + if (req->method == HTTP_HEAD) { + flags |= F_SKIPBODY; + } else { + flags &= ~F_SKIPBODY; + } + } + return 0; + } + + virtual int InitResponse(HttpResponse* res) { + res->Reset(); + parsed = res; + http_parser_init(&parser, HTTP_RESPONSE); + url.clear(); + header_field.clear(); + header_value.clear(); + return 0; + } + + // server + // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} + virtual int InitRequest(HttpRequest* req) { + req->Reset(); + parsed = req; + http_parser_init(&parser, HTTP_REQUEST); + state = HP_START_REQ_OR_RES; + url.clear(); + header_field.clear(); + header_value.clear(); + return 0; + } + + virtual int SubmitResponse(HttpResponse* res) { + submited = res; + return 0; + } + + // HttpMessage::http_cb + int invokeHttpCb(const char* data = NULL, size_t size = 0) { + if (parsed->http_cb == NULL) return -1; + parsed->http_cb(parsed, state, data, size); + return 0; + } +}; + +#endif // HV_HTTP1_PARSER_H_ diff --git a/external/libhv/libhv-1.3.2/http/Http2Parser.cpp b/external/libhv/libhv-1.3.2/http/Http2Parser.cpp new file mode 100644 index 0000000..18c2241 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/Http2Parser.cpp @@ -0,0 +1,433 @@ +#ifdef WITH_NGHTTP2 + +#include "Http2Parser.h" + +static nghttp2_nv make_nv(const char* name, const char* value) { + nghttp2_nv nv; + nv.name = (uint8_t*)name; + nv.value = (uint8_t*)value; + nv.namelen = strlen(name); + nv.valuelen = strlen(value); + nv.flags = NGHTTP2_NV_FLAG_NONE; + return nv; +} + +static nghttp2_nv make_nv2(const char* name, const char* value, + int namelen, int valuelen) { + nghttp2_nv nv; + nv.name = (uint8_t*)name; + nv.value = (uint8_t*)value; + nv.namelen = namelen; nv.valuelen = valuelen; + nv.flags = NGHTTP2_NV_FLAG_NONE; + return nv; +} + +static void print_frame_hd(const nghttp2_frame_hd* hd) { + printd("[frame] length=%d type=%x flags=%x stream_id=%d\n", + (int)hd->length, (int)hd->type, (int)hd->flags, hd->stream_id); +} +static int on_header_callback(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *name, size_t namelen, + const uint8_t *value, size_t valuelen, + uint8_t flags, void *userdata); +static int on_data_chunk_recv_callback(nghttp2_session *session, + uint8_t flags, int32_t stream_id, const uint8_t *data, + size_t len, void *userdata); +static int on_frame_recv_callback(nghttp2_session *session, + const nghttp2_frame *frame, void *userdata); +/* +static ssize_t data_source_read_callback(nghttp2_session *session, + int32_t stream_id, uint8_t *buf, size_t length, + uint32_t *data_flags, nghttp2_data_source *source, void *userdata); +*/ + + +Http2Parser::Http2Parser(http_session_type type) { + if (cbs == NULL) { + nghttp2_session_callbacks_new(&cbs); + nghttp2_session_callbacks_set_on_header_callback(cbs, on_header_callback); + nghttp2_session_callbacks_set_on_data_chunk_recv_callback(cbs, on_data_chunk_recv_callback); + nghttp2_session_callbacks_set_on_frame_recv_callback(cbs, on_frame_recv_callback); + } + if (type == HTTP_CLIENT) { + nghttp2_session_client_new(&session, cbs, this); + state = H2_SEND_MAGIC; + } + else if (type == HTTP_SERVER) { + nghttp2_session_server_new(&session, cbs, this); + state = H2_WANT_RECV; + } + //nghttp2_session_set_user_data(session, this); + submited = NULL; + parsed = NULL; + stream_id = -1; + stream_closed = 0; + + nghttp2_settings_entry settings[] = { + {NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 100} + }; + nghttp2_submit_settings(session, NGHTTP2_FLAG_NONE, settings, ARRAY_SIZE(settings)); + state = H2_SEND_SETTINGS; + + //nghttp2_submit_ping(session, NGHTTP2_FLAG_NONE, NULL); + //state = H2_SEND_PING; +} + +Http2Parser::~Http2Parser() { + if (session) { + nghttp2_session_del(session); + session = NULL; + } +} + +int Http2Parser::GetSendData(char** data, size_t* len) { + // HTTP2_MAGIC,HTTP2_SETTINGS,HTTP2_HEADERS + *len = nghttp2_session_mem_send(session, (const uint8_t**)data); + printd("nghttp2_session_mem_send %d\n", *len); + if (*len != 0) return *len; + + if (submited == NULL) return 0; + // HTTP2_DATA + if (state == H2_SEND_HEADERS) { + void* content = submited->Content(); + int content_length = submited->ContentLength(); + // HTTP2 DATA framehd + state = H2_SEND_DATA_FRAME_HD; + http2_frame_hd framehd; + framehd.length = content_length; + framehd.type = HTTP2_DATA; + framehd.flags = HTTP2_FLAG_END_STREAM; + framehd.stream_id = stream_id; + *data = (char*)frame_hdbuf; + *len = HTTP2_FRAME_HDLEN; + printd("HTTP2 SEND_DATA_FRAME_HD...\n"); + if (submited->ContentType() == APPLICATION_GRPC) { + grpc_message_hd msghd; + msghd.flags = 0; + msghd.length = content_length; + printd("grpc_message_hd: flags=%d length=%d\n", msghd.flags, msghd.length); + + if (type == HTTP_SERVER) { + // grpc server send grpc-status in HTTP2 header frame + framehd.flags = HTTP2_FLAG_NONE; + + /* + // @test protobuf + // message StringMessage { + // string str = 1; + // } + int protobuf_taglen = 0; + int tag = PROTOBUF_MAKE_TAG(1, WIRE_TYPE_LENGTH_DELIMITED); + unsigned char* p = frame_hdbuf + HTTP2_FRAME_HDLEN + GRPC_MESSAGE_HDLEN; + int bytes = varint_encode(tag, p); + protobuf_taglen += bytes; + p += bytes; + bytes = varint_encode(content_length, p); + protobuf_taglen += bytes; + msghd.length += protobuf_taglen; + framehd.length += protobuf_taglen; + *len += protobuf_taglen; + */ + } + + grpc_message_hd_pack(&msghd, frame_hdbuf + HTTP2_FRAME_HDLEN); + framehd.length += GRPC_MESSAGE_HDLEN; + *len += GRPC_MESSAGE_HDLEN; + } + http2_frame_hd_pack(&framehd, frame_hdbuf); + } + else if (state == H2_SEND_DATA_FRAME_HD) { + // HTTP2 DATA + void* content = submited->Content(); + int content_length = submited->ContentLength(); + if (content_length == 0) { + // skip send_data + goto send_done; + } + else { + printd("HTTP2 SEND_DATA... content_length=%d\n", content_length); + state = H2_SEND_DATA; + *data = (char*)content; + *len = content_length; + } + } + else if (state == H2_SEND_DATA) { +send_done: + state = H2_SEND_DONE; + if (submited->ContentType() == APPLICATION_GRPC) { + if (type == HTTP_SERVER && stream_closed) { + // grpc HEADERS grpc-status + printd("grpc HEADERS grpc-status: 0\n"); + int flags = NGHTTP2_FLAG_END_STREAM | NGHTTP2_FLAG_END_HEADERS; + nghttp2_nv nv = make_nv("grpc-status", "0"); + nghttp2_submit_headers(session, flags, stream_id, NULL, &nv, 1, NULL); + *len = nghttp2_session_mem_send(session, (const uint8_t**)data); + } + } + } + + printd("GetSendData %d\n", *len); + return *len; +} + +int Http2Parser::FeedRecvData(const char* data, size_t len) { + printd("nghttp2_session_mem_recv %d\n", len); + state = H2_WANT_RECV; + size_t ret = nghttp2_session_mem_recv(session, (const uint8_t*)data, len); + if (ret != len) { + error = ret; + } + return (int)ret; +} + +int Http2Parser::SubmitRequest(HttpRequest* req) { + submited = req; + + req->FillContentType(); + req->FillContentLength(); + if (req->ContentType() == APPLICATION_GRPC) { + req->method = HTTP_POST; + req->headers["te"] = "trailers"; + req->headers["user-agent"] = "grpc-c++/1.16.0 grpc-c/6.0.0 (linux; nghttp2; hw)"; + req->headers["accept-encoding"] = "identity"; + req->headers["grpc-accept-encoding"] = "identity"; + } + + std::vector nvs; + char c_str[256] = {0}; + req->ParseUrl(); + nvs.push_back(make_nv(":method", http_method_str(req->method))); + nvs.push_back(make_nv(":path", req->path.c_str())); + nvs.push_back(make_nv(":scheme", req->scheme.c_str())); + if (req->port == 0 || + req->port == DEFAULT_HTTP_PORT || + req->port == DEFAULT_HTTPS_PORT) { + nvs.push_back(make_nv(":authority", req->host.c_str())); + } + else { + snprintf(c_str, sizeof(c_str), "%s:%d", req->host.c_str(), req->port); + nvs.push_back(make_nv(":authority", c_str)); + } + const char* name; + const char* value; + for (auto& header : req->headers) { + name = header.first.c_str(); + value = header.second.c_str(); + hv_strlower((char*)name); + if (strcmp(name, "host") == 0) { + // :authority + continue; + } + if (strcmp(name, "connection") == 0) { + // HTTP2 default keep-alive + continue; + } + if (strcmp(name, "content-length") == 0) { + // HTTP2 have frame_hd.length + continue; + } + nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size())); + } + int flags = NGHTTP2_FLAG_END_HEADERS; + // we set EOS on DATA frame + stream_id = nghttp2_submit_headers(session, flags, -1, NULL, &nvs[0], nvs.size(), NULL); + // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data + // nghttp2_data_provider data_prd; + // data_prd.read_callback = data_source_read_callback; + //stream_id = nghttp2_submit_request(session, NULL, &nvs[0], nvs.size(), &data_prd, NULL); + state = H2_SEND_HEADERS; + return 0; +} + +int Http2Parser::SubmitResponse(HttpResponse* res) { + submited = res; + + res->FillContentType(); + res->FillContentLength(); + if (parsed && parsed->ContentType() == APPLICATION_GRPC) { + // correct content_type: application/grpc + if (res->ContentType() != APPLICATION_GRPC) { + res->content_type = APPLICATION_GRPC; + res->headers["content-type"] = http_content_type_str(APPLICATION_GRPC); + } + //res->headers["accept-encoding"] = "identity"; + //res->headers["grpc-accept-encoding"] = "identity"; + //res->headers["grpc-status"] = "0"; + //res->status_code = HTTP_STATUS_OK; + } + + std::vector nvs; + char c_str[256] = {0}; + snprintf(c_str, sizeof(c_str), "%d", res->status_code); + nvs.push_back(make_nv(":status", c_str)); + const char* name; + const char* value; + for (auto& header : res->headers) { + name = header.first.c_str(); + value = header.second.c_str(); + hv_strlower((char*)name); + if (strcmp(name, "connection") == 0) { + // HTTP2 default keep-alive + continue; + } + if (strcmp(name, "content-length") == 0) { + // HTTP2 have frame_hd.length + continue; + } + nvs.push_back(make_nv2(name, value, header.first.size(), header.second.size())); + } + int flags = NGHTTP2_FLAG_END_HEADERS; + // we set EOS on DATA frame + if (stream_id == -1) { + // upgrade + nghttp2_session_upgrade(session, NULL, 0, NULL); + stream_id = 1; + } + nghttp2_submit_headers(session, flags, stream_id, NULL, &nvs[0], nvs.size(), NULL); + // avoid DATA_SOURCE_COPY, we do not use nghttp2_submit_data + // data_prd.read_callback = data_source_read_callback; + //nghttp2_submit_response(session, stream_id, &nvs[0], nvs.size(), &data_prd); + state = H2_SEND_HEADERS; + return 0; +} + +int Http2Parser::InitResponse(HttpResponse* res) { + res->Reset(); + res->http_major = 2; + res->http_minor = 0; + parsed = res; + return 0; +} + +int Http2Parser::InitRequest(HttpRequest* req) { + req->Reset(); + req->http_major = 2; + req->http_minor = 0; + parsed = req; + return 0; +} + +nghttp2_session_callbacks* Http2Parser::cbs = NULL; + +int on_header_callback(nghttp2_session *session, + const nghttp2_frame *frame, + const uint8_t *_name, size_t namelen, + const uint8_t *_value, size_t valuelen, + uint8_t flags, void *userdata) { + printd("on_header_callback\n"); + print_frame_hd(&frame->hd); + const char* name = (const char*)_name; + const char* value = (const char*)_value; + printd("%s: %s\n", name, value); + Http2Parser* hp = (Http2Parser*)userdata; + if (*name == ':') { + if (hp->parsed->type == HTTP_REQUEST) { + // :method :path :scheme :authority + HttpRequest* req = (HttpRequest*)hp->parsed; + if (strcmp(name, ":method") == 0) { + req->method = http_method_enum(value); + } + else if (strcmp(name, ":path") == 0) { + req->url = value; + } + else if (strcmp(name, ":scheme") == 0) { + req->headers["Scheme"] = value; + } + else if (strcmp(name, ":authority") == 0) { + req->headers["Host"] = value; + } + } + else if (hp->parsed->type == HTTP_RESPONSE) { + HttpResponse* res = (HttpResponse*)hp->parsed; + if (strcmp(name, ":status") == 0) { + res->status_code = (http_status)atoi(value); + if (res->http_cb) { + res->http_cb(res, HP_MESSAGE_BEGIN, NULL, 0); + } + } + } + } + else { + hp->parsed->headers[name] = value; + if (strcmp(name, "content-type") == 0) { + hp->parsed->content_type = http_content_type_enum(value); + } + } + return 0; +} + +int on_data_chunk_recv_callback(nghttp2_session *session, + uint8_t flags, int32_t stream_id, const uint8_t *data, + size_t len, void *userdata) { + printd("on_data_chunk_recv_callback\n"); + printd("stream_id=%d length=%d\n", stream_id, (int)len); + //printd("%.*s\n", (int)len, data); + Http2Parser* hp = (Http2Parser*)userdata; + + if (hp->parsed->ContentType() == APPLICATION_GRPC) { + // grpc_message_hd + if (len >= GRPC_MESSAGE_HDLEN) { + grpc_message_hd msghd; + grpc_message_hd_unpack(&msghd, data); + printd("grpc_message_hd: flags=%d length=%d\n", msghd.flags, msghd.length); + data += GRPC_MESSAGE_HDLEN; + len -= GRPC_MESSAGE_HDLEN; + //printd("%.*s\n", (int)len, data); + } + } + if (hp->parsed->http_cb) { + hp->parsed->http_cb(hp->parsed, HP_BODY, (const char*)data, len); + } else { + hp->parsed->body.append((const char*)data, len); + } + return 0; +} + +int on_frame_recv_callback(nghttp2_session *session, + const nghttp2_frame *frame, void *userdata) { + printd("on_frame_recv_callback\n"); + print_frame_hd(&frame->hd); + Http2Parser* hp = (Http2Parser*)userdata; + switch (frame->hd.type) { + case NGHTTP2_DATA: + hp->state = H2_RECV_DATA; + break; + case NGHTTP2_HEADERS: + hp->state = H2_RECV_HEADERS; + break; + case NGHTTP2_SETTINGS: + hp->state = H2_RECV_SETTINGS; + break; + case NGHTTP2_PING: + hp->state = H2_RECV_PING; + break; + case NGHTTP2_RST_STREAM: + case NGHTTP2_WINDOW_UPDATE: + // ignore + return 0; + default: + break; + } + if (hp->state == H2_RECV_HEADERS && hp->parsed->http_cb) { + hp->parsed->http_cb(hp->parsed, HP_HEADERS_COMPLETE, NULL, 0); + } + if (frame->hd.stream_id >= hp->stream_id) { + hp->stream_id = frame->hd.stream_id; + hp->stream_closed = 0; + if (frame->hd.flags & NGHTTP2_FLAG_END_STREAM) { + printd("on_stream_closed stream_id=%d\n", hp->stream_id); + hp->stream_closed = 1; + hp->frame_type_when_stream_closed = frame->hd.type; + if (hp->state == H2_RECV_HEADERS || hp->state == H2_RECV_DATA) { + if (hp->parsed->http_cb) { + hp->parsed->http_cb(hp->parsed, HP_MESSAGE_COMPLETE, NULL, 0); + } + } + } + } + + return 0; +} + +#endif diff --git a/external/libhv/libhv-1.3.2/http/Http2Parser.h b/external/libhv/libhv-1.3.2/http/Http2Parser.h new file mode 100644 index 0000000..719f449 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/Http2Parser.h @@ -0,0 +1,89 @@ +#ifndef HV_HTTP2_PARSER_H_ +#define HV_HTTP2_PARSER_H_ + +#ifdef WITH_NGHTTP2 +#include "HttpParser.h" +#include "http2def.h" +#include "grpcdef.h" + +#include "nghttp2/nghttp2.h" + +enum http2_session_state { + H2_SEND_MAGIC, + H2_SEND_SETTINGS, + H2_SEND_PING, + H2_SEND_HEADERS, + H2_SEND_DATA_FRAME_HD, + H2_SEND_DATA, + H2_SEND_DONE, + + H2_WANT_SEND, + H2_WANT_RECV, + + H2_RECV_SETTINGS, + H2_RECV_PING, + H2_RECV_HEADERS, + H2_RECV_DATA, +}; + +class Http2Parser : public HttpParser { +public: + static nghttp2_session_callbacks* cbs; + nghttp2_session* session; + http2_session_state state; + HttpMessage* submited; + HttpMessage* parsed; + int error; + int stream_id; + int stream_closed; + int frame_type_when_stream_closed; + // http2_frame_hd + grpc_message_hd + // at least HTTP2_FRAME_HDLEN + GRPC_MESSAGE_HDLEN = 9 + 5 = 14 + unsigned char frame_hdbuf[32]; + + Http2Parser(http_session_type type = HTTP_CLIENT); + virtual ~Http2Parser(); + + virtual int GetSendData(char** data, size_t* len); + virtual int FeedRecvData(const char* data, size_t len); + + virtual int GetState() { + return (int)state; + } + + virtual bool WantRecv() { + return state == H2_WANT_RECV; + } + + virtual bool WantSend() { + return state <= H2_WANT_SEND; + } + + virtual bool IsComplete() { + return stream_closed && (frame_type_when_stream_closed == HTTP2_DATA || frame_type_when_stream_closed == HTTP2_HEADERS); + } + + virtual int GetError() { + return error; + } + + virtual const char* StrError(int error) { + //return nghttp2_http2_strerror(error); + return nghttp2_strerror(error); + } + + // client + // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) + virtual int SubmitRequest(HttpRequest* req); + virtual int InitResponse(HttpResponse* res); + + // server + // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} + virtual int InitRequest(HttpRequest* req); + virtual int SubmitResponse(HttpResponse* res); + +}; + +#endif + +#endif // HV_HTTP2_PARSER_H_ diff --git a/external/libhv/libhv-1.3.2/http/HttpMessage.cpp b/external/libhv/libhv-1.3.2/http/HttpMessage.cpp new file mode 100644 index 0000000..42ea94d --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/HttpMessage.cpp @@ -0,0 +1,858 @@ +#include "HttpMessage.h" + +#include + +#include "htime.h" +#include "hlog.h" +#include "hurl.h" +#include "base64.h" + +using namespace hv; + +http_headers DefaultHeaders; +http_body NoBody; +HttpCookie NoCookie; +char HttpMessage::s_date[32] = {0}; + +HttpCookie::HttpCookie() { + init(); +} + +void HttpCookie::init() { + max_age = 0; + secure = false; + httponly = false; + samesite = Default; + priority = NotSet; +} + +void HttpCookie::reset() { + init(); + name.clear(); + value.clear(); + domain.clear(); + path.clear(); + expires.clear(); + kv.clear(); +} + +bool HttpCookie::parse(const std::string& str) { + std::stringstream ss; + ss << str; + std::string line; + std::string::size_type pos; + std::string key; + std::string val; + + reset(); + while (std::getline(ss, line, ';')) { + pos = line.find_first_of('='); + if (pos != std::string::npos) { + key = trim(line.substr(0, pos)); + val = trim(line.substr(pos+1)); + const char* pkey = key.c_str(); + if (stricmp(pkey, "Domain") == 0) { + domain = val; + } + else if (stricmp(pkey, "Path") == 0) { + path = val; + } + else if (stricmp(pkey, "Expires") == 0) { + expires = val; + } + else if (stricmp(pkey, "Max-Age") == 0) { + max_age = atoi(val.c_str()); + } + else if (stricmp(pkey, "SameSite") == 0) { + samesite = stricmp(val.c_str(), "Strict") == 0 ? HttpCookie::SameSite::Strict : + stricmp(val.c_str(), "Lax") == 0 ? HttpCookie::SameSite::Lax : + stricmp(val.c_str(), "None") == 0 ? HttpCookie::SameSite::None : + HttpCookie::SameSite::Default; + } + else if (stricmp(pkey, "Priority") == 0) { + priority = stricmp(val.c_str(), "Low") == 0 ? HttpCookie::Priority::Low : + stricmp(val.c_str(), "Medium") == 0 ? HttpCookie::Priority::Medium : + stricmp(val.c_str(), "High") == 0 ? HttpCookie::Priority::High : + HttpCookie::Priority::NotSet ; + } + else { + if (name.empty()) { + name = key; + value = val; + } + kv[key] = val; + } + } else { + key = trim(line); + const char* pkey = key.c_str(); + if (stricmp(pkey, "Secure") == 0) { + secure = true; + } + else if (stricmp(pkey, "HttpOnly") == 0) { + httponly = true; + } + else { + hlogw("Unrecognized key '%s'", key.c_str()); + } + } + + } + return !name.empty(); +} + +std::string HttpCookie::dump() const { + assert(!name.empty() || !kv.empty()); + std::string res; + + if (!name.empty()) { + res = name; + res += "="; + res += value; + } + + for (auto& pair : kv) { + if (pair.first == name) continue; + if (!res.empty()) res += "; "; + res += pair.first; + res += "="; + res += pair.second; + } + + if (!domain.empty()) { + res += "; Domain="; + res += domain; + } + + if (!path.empty()) { + res += "; Path="; + res += path; + } + + if (max_age > 0) { + res += "; Max-Age="; + res += hv::to_string(max_age); + } else if (!expires.empty()) { + res += "; Expires="; + res += expires; + } + + if (samesite != HttpCookie::SameSite::Default) { + res += "; SameSite="; + res += samesite == HttpCookie::SameSite::Strict ? "Strict" : + samesite == HttpCookie::SameSite::Lax ? "Lax" : + "None" ; + } + + if (priority != HttpCookie::Priority::NotSet) { + res += "; Priority="; + res += priority == HttpCookie::Priority::Low ? "Low" : + priority == HttpCookie::Priority::Medium ? "Medium" : + "High" ; + } + + if (secure) { + res += "; Secure"; + } + + if (httponly) { + res += "; HttpOnly"; + } + + return res; +} + +HttpMessage::HttpMessage() { + type = HTTP_BOTH; + Init(); +} + +HttpMessage::~HttpMessage() { + +} + +void HttpMessage::Init() { + http_major = 1; + http_minor = 1; + content = NULL; + content_length = 0; + content_type = CONTENT_TYPE_NONE; +} + +void HttpMessage::Reset() { + Init(); + headers.clear(); + cookies.clear(); + body.clear(); +#ifndef WITHOUT_HTTP_CONTENT + json.clear(); + form.clear(); + kv.clear(); +#endif +} + +#ifndef WITHOUT_HTTP_CONTENT +// NOTE: json ignore number/string, 123/"123" + +std::string HttpMessage::GetString(const char* key, const std::string& defvalue) { + switch (ContentType()) { + case APPLICATION_JSON: + { + if (json.empty()) { + ParseBody(); + } + if (!json.is_object()) { + return defvalue; + } + const auto& value = json[key]; + if (value.is_string()) { + return value; + } + else if (value.is_number()) { + return hv::to_string(value); + } + else if (value.is_boolean()) { + bool b = value; + return b ? "true" : "false"; + } + else { + return defvalue; + } + } + break; + case MULTIPART_FORM_DATA: + { + if (form.empty()) { + ParseBody(); + } + auto iter = form.find(key); + if (iter != form.end()) { + return iter->second.content; + } + } + break; + case APPLICATION_URLENCODED: + { + if (kv.empty()) { + ParseBody(); + } + auto iter = kv.find(key); + if (iter != kv.end()) { + return iter->second; + } + } + break; + default: + break; + } + return defvalue; +} + +template<> +HV_EXPORT int64_t HttpMessage::Get(const char* key, int64_t defvalue) { + if (ContentType() == APPLICATION_JSON) { + if (json.empty()) { + ParseBody(); + } + if (!json.is_object()) { + return defvalue; + } + const auto& value = json[key]; + if (value.is_number()) { + return value; + } + else if (value.is_string()) { + std::string str = value; + return atoll(str.c_str()); + } + else if (value.is_boolean()) { + bool b = value; + return b ? 1 : 0; + } + else { + return defvalue; + } + } + else { + std::string str = GetString(key); + return str.empty() ? defvalue : atoll(str.c_str()); + } +} + +template<> +HV_EXPORT int HttpMessage::Get(const char* key, int defvalue) { + return (int)Get(key, defvalue); +} + +template<> +HV_EXPORT double HttpMessage::Get(const char* key, double defvalue) { + if (ContentType() == APPLICATION_JSON) { + if (json.empty()) { + ParseBody(); + } + if (!json.is_object()) { + return defvalue; + } + const auto& value = json[key]; + if (value.is_number()) { + return value; + } + else if (value.is_string()) { + std::string str = value; + return atof(str.c_str()); + } + else { + return defvalue; + } + } + else { + std::string str = GetString(key); + return str.empty() ? defvalue : atof(str.c_str()); + } +} + +template<> +HV_EXPORT float HttpMessage::Get(const char* key, float defvalue) { + return (float)Get(key, defvalue); +} + +template<> +HV_EXPORT bool HttpMessage::Get(const char* key, bool defvalue) { + if (ContentType() == APPLICATION_JSON) { + if (json.empty()) { + ParseBody(); + } + if (!json.is_object()) { + return defvalue; + } + const auto& value = json[key]; + if (value.is_boolean()) { + return value; + } + else if (value.is_string()) { + std::string str = value; + return hv_getboolean(str.c_str()); + } + else if (value.is_number()) { + return value != 0; + } + else { + return defvalue; + } + } + else { + std::string str = GetString(key); + return str.empty() ? defvalue : hv_getboolean(str.c_str()); + } +} + +bool HttpMessage::GetBool(const char* key, bool defvalue) { + return Get(key, defvalue); +} +int64_t HttpMessage::GetInt(const char* key, int64_t defvalue) { + return Get(key, defvalue); +} +double HttpMessage::GetFloat(const char* key, double defvalue) { + return Get(key, defvalue); +} +#endif + +void HttpMessage::FillContentType() { + auto iter = headers.find("Content-Type"); + if (iter != headers.end()) { + content_type = http_content_type_enum(iter->second.c_str()); + goto append; + } + +#ifndef WITHOUT_HTTP_CONTENT + if (content_type == CONTENT_TYPE_NONE) { + if (json.size() != 0) { + content_type = APPLICATION_JSON; + } + else if (form.size() != 0) { + content_type = MULTIPART_FORM_DATA; + } + else if (kv.size() != 0) { + content_type = X_WWW_FORM_URLENCODED; + } + else if (body.size() != 0) { + content_type = TEXT_PLAIN; + } + } +#endif + + if (content_type != CONTENT_TYPE_NONE) { + headers["Content-Type"] = http_content_type_str(content_type); + } + +append: +#ifndef WITHOUT_HTTP_CONTENT + if (content_type == MULTIPART_FORM_DATA) { + auto iter = headers.find("Content-Type"); + if (iter != headers.end()) { + const char* boundary = strstr(iter->second.c_str(), "boundary="); + if (boundary == NULL) { + boundary = DEFAULT_MULTIPART_BOUNDARY; + iter->second += "; boundary="; + iter->second += boundary; + } + } + } +#endif + return; +} + +void HttpMessage::FillContentLength() { + auto iter = headers.find("Content-Length"); + if (iter != headers.end()) { + content_length = atoll(iter->second.c_str()); + } + if (content_length == 0) { + DumpBody(); + content_length = body.size(); + } + if (iter == headers.end() && !IsChunked() && content_type != TEXT_EVENT_STREAM) { + if (content_length != 0 || type == HTTP_RESPONSE) { + headers["Content-Length"] = hv::to_string(content_length); + } + } +} + +bool HttpMessage::IsChunked() { + auto iter = headers.find("Transfer-Encoding"); + return iter != headers.end() && stricmp(iter->second.c_str(), "chunked") == 0; +} + +bool HttpMessage::IsKeepAlive() { + bool keepalive = true; + auto iter = headers.find("connection"); + if (iter != headers.end()) { + const char* keepalive_value = iter->second.c_str(); + if (stricmp(keepalive_value, "keep-alive") == 0) { + keepalive = true; + } + else if (stricmp(keepalive_value, "close") == 0) { + keepalive = false; + } + else if (stricmp(keepalive_value, "upgrade") == 0) { + keepalive = true; + } + } + else if (http_major == 1 && http_minor == 0) { + keepalive = false; + } + return keepalive; +} + +bool HttpMessage::IsUpgrade() { + auto iter = headers.find("upgrade"); + return iter != headers.end(); +} + +// headers +void HttpMessage::SetHeader(const char* key, const std::string& value) { + headers[key] = value; +} +std::string HttpMessage::GetHeader(const char* key, const std::string& defvalue) { + auto iter = headers.find(key); + return iter == headers.end() ? defvalue : iter->second; +} + +// cookies +void HttpMessage::AddCookie(const HttpCookie& cookie) { + cookies.push_back(cookie); +} +const HttpCookie& HttpMessage::GetCookie(const std::string& name) { + for (auto iter = cookies.begin(); iter != cookies.end(); ++iter) { + if (iter->name == name) { + return *iter; + } + } + return NoCookie; +} + +// body +void HttpMessage::SetBody(const std::string& body) { + this->body = body; +} +const std::string& HttpMessage::Body() { + return this->body; +} + +void HttpMessage::DumpHeaders(std::string& str) { + FillContentType(); + FillContentLength(); + + // headers + for (auto& header: headers) { + // http2 :method :path :scheme :authority :status + if (*str.c_str() != ':') { + // %s: %s\r\n + str += header.first; + str += ": "; + // if the value has \r\n, translate to \\r\\n + if (header.second.find("\r") != std::string::npos || + header.second.find("\n") != std::string::npos) { + std::string newStr = ""; + for (size_t i = 0; i < header.second.size(); ++i) { + if (header.second[i] == '\r') { + newStr += "\\r"; + } else if (header.second[i] == '\n') { + newStr += "\\n"; + } else { + newStr += header.second[i]; + } + } + str += newStr; + } else { + str += header.second; + } + str += "\r\n"; + } + } + + // cookies + const char* cookie_field = "Cookie"; + if (type == HTTP_RESPONSE) { + cookie_field = "Set-Cookie"; + } + for (auto& cookie : cookies) { + str += cookie_field; + str += ": "; + str += cookie.dump(); + str += "\r\n"; + } +} + +void HttpMessage::DumpBody() { + if (body.size() != 0) { + return; + } + FillContentType(); +#ifndef WITHOUT_HTTP_CONTENT + switch(content_type) { + case APPLICATION_JSON: + body = dump_json(json, 2); + break; + case MULTIPART_FORM_DATA: + { + auto iter = headers.find("Content-Type"); + if (iter == headers.end()) { + return; + } + const char* boundary = strstr(iter->second.c_str(), "boundary="); + if (boundary == NULL) { + return; + } + boundary += strlen("boundary="); + body = dump_multipart(form, boundary); + } + break; + case X_WWW_FORM_URLENCODED: + body = dump_query_params(kv); + break; + default: + // nothing to do + break; + } +#endif +} + +void HttpMessage::DumpBody(std::string& str) { + DumpBody(); + const char* content = (const char*)Content(); + size_t content_length = ContentLength(); + if (content && content_length) { + str.append(content, content_length); + } +} + +int HttpMessage::ParseBody() { + if (body.size() == 0) { + return -1; + } + FillContentType(); +#ifndef WITHOUT_HTTP_CONTENT + switch(content_type) { + case APPLICATION_JSON: + { + std::string errmsg; + int ret = parse_json(body.c_str(), json, errmsg); + if (ret != 0 && errmsg.size() != 0) { + hloge("%s", errmsg.c_str()); + } + return ret; + } + case MULTIPART_FORM_DATA: + { + auto iter = headers.find("Content-Type"); + if (iter == headers.end()) { + return -1; + } + const char* boundary = strstr(iter->second.c_str(), "boundary="); + if (boundary == NULL) { + return -1; + } + boundary += strlen("boundary="); + std::string strBoundary(boundary); + strBoundary = trim_pairs(strBoundary, "\"\"\'\'"); + return parse_multipart(body, form, strBoundary.c_str()); + } + case X_WWW_FORM_URLENCODED: + return parse_query_params(body.c_str(), kv); + default: + // nothing to do + return 0; + } +#endif + return 0; +} + +std::string HttpMessage::Dump(bool is_dump_headers, bool is_dump_body) { + std::string str; + if (is_dump_headers) { + DumpHeaders(str); + } + str += "\r\n"; + if (is_dump_body) { + DumpBody(str); + } + return str; +} + + +HttpRequest::HttpRequest() : HttpMessage() { + type = HTTP_REQUEST; + Init(); +} + +void HttpRequest::Init() { + headers["User-Agent"] = DEFAULT_HTTP_USER_AGENT; + headers["Accept"] = "*/*"; + method = HTTP_GET; + scheme = "http"; + host = "127.0.0.1"; + port = DEFAULT_HTTP_PORT; + path = "/"; + timeout = DEFAULT_HTTP_TIMEOUT; + connect_timeout = DEFAULT_HTTP_CONNECT_TIMEOUT; + retry_count = DEFAULT_HTTP_FAIL_RETRY_COUNT; + retry_delay = DEFAULT_HTTP_FAIL_RETRY_DELAY; + redirect = 1; + proxy = 0; + cancel = 0; +} + +void HttpRequest::Reset() { + HttpMessage::Reset(); + Init(); + url.clear(); + query_params.clear(); +} + +void HttpRequest::DumpUrl() { + std::string str; + if (url.size() != 0 && + *url.c_str() != '/' && + strstr(url.c_str(), "://") != NULL) { + // have been complete url + goto query; + } + // scheme:// + str = scheme; + str += "://"; + // host:port + if (url.size() != 0 && *url.c_str() != '/') { + // url begin with host + str += url; + } + else { + if (port == 0 || + port == DEFAULT_HTTP_PORT || + port == DEFAULT_HTTPS_PORT) { + str += Host(); + } + else { + str += hv::asprintf("%s:%d", host.c_str(), port); + } + } + // /path + if (url.size() != 0 && *url.c_str() == '/') { + // url begin with path + str += url; + } + else if (path.size() > 1 && *path.c_str() == '/') { + str += path; + } + else if (url.size() == 0) { + str += '/'; + } + url = str; +query: + // ?query + if (strchr(url.c_str(), '?') == NULL && + query_params.size() != 0) { + url += '?'; + url += dump_query_params(query_params); + } +} + +void HttpRequest::ParseUrl() { + DumpUrl(); + hurl_t parser; + hv_parse_url(&parser, url.c_str()); + // scheme + std::string scheme_ = url.substr(parser.fields[HV_URL_SCHEME].off, parser.fields[HV_URL_SCHEME].len); + // host + std::string host_(host); + if (parser.fields[HV_URL_HOST].len > 0) { + host_ = url.substr(parser.fields[HV_URL_HOST].off, parser.fields[HV_URL_HOST].len); + } + // port + int port_ = parser.port ? parser.port : strcmp(scheme_.c_str(), "https") ? DEFAULT_HTTP_PORT : DEFAULT_HTTPS_PORT; + if (!proxy) { + scheme = scheme_; + host = host_; + port = port_; + } + FillHost(host_.c_str(), port_); + // path + if (parser.fields[HV_URL_PATH].len > 0) { + path = url.substr(parser.fields[HV_URL_PATH].off); + } + // query + if (parser.fields[HV_URL_QUERY].len > 0) { + parse_query_params(url.c_str()+parser.fields[HV_URL_QUERY].off, query_params); + } +} + +std::string HttpRequest::Path() { + const char* s = path.c_str(); + const char* e = s; + while (*e && *e != '?' && *e != '#') ++e; + return HUrl::unescape(std::string(s, e)); +} + +void HttpRequest::FillHost(const char* host, int port) { + if (headers.find("Host") == headers.end()) { + if (port == 0 || + port == DEFAULT_HTTP_PORT || + port == DEFAULT_HTTPS_PORT) { + headers["Host"] = host; + } else { + headers["Host"] = asprintf("%s:%d", host, port); + } + } +} + +void HttpRequest::SetHost(const char* host, int port) { + this->host = host; + this->port = port; + FillHost(host, port); +} + +void HttpRequest::SetProxy(const char* host, int port) { + this->scheme = "http"; + this->host = host; + this->port = port; + proxy = 1; +} + +void HttpRequest::SetAuth(const std::string& auth) { + SetHeader("Authorization", auth); +} + +void HttpRequest::SetBasicAuth(const std::string& username, const std::string& password) { + std::string strAuth = hv::asprintf("%s:%s", username.c_str(), password.c_str()); + std::string base64Auth = hv::Base64Encode((const unsigned char*)strAuth.c_str(), strAuth.size()); + SetAuth(std::string("Basic ") + base64Auth); +} + +void HttpRequest::SetBearerTokenAuth(const std::string& token) { + SetAuth(std::string("Bearer ") + token); +} + +std::string HttpRequest::Dump(bool is_dump_headers, bool is_dump_body) { + ParseUrl(); + + std::string str; + str.reserve(MAX(512, path.size() + 128)); + // GET / HTTP/1.1\r\n + str = asprintf("%s %s HTTP/%d.%d\r\n", + http_method_str(method), + proxy ? url.c_str() : path.c_str(), + (int)http_major, (int)http_minor); + if (is_dump_headers) { + DumpHeaders(str); + } + str += "\r\n"; + if (is_dump_body) { + DumpBody(str); + } + return str; +} + +void HttpRequest::SetRange(long from, long to) { + SetHeader("Range", hv::asprintf("bytes=%ld-%ld", from, to)); +} + +bool HttpRequest::GetRange(long& from, long& to) { + auto iter = headers.find("Range"); + if (iter != headers.end()) { + sscanf(iter->second.c_str(), "bytes=%ld-%ld", &from, &to); + return true; + } + from = to = 0; + return false; +} + +HttpResponse::HttpResponse() : HttpMessage() { + type = HTTP_RESPONSE; + Init(); +} + +void HttpResponse::Init() { + status_code = HTTP_STATUS_OK; +} + +void HttpResponse::Reset() { + HttpMessage::Reset(); + Init(); +} + +std::string HttpResponse::Dump(bool is_dump_headers, bool is_dump_body) { + char c_str[256] = {0}; + std::string str; + str.reserve(512); + // HTTP/1.1 200 OK\r\n + snprintf(c_str, sizeof(c_str), "HTTP/%d.%d %d %s\r\n", + (int)http_major, (int)http_minor, + (int)status_code, http_status_str(status_code)); + str = c_str; + if (is_dump_headers) { + if (*s_date) { + headers["Date"] = s_date; + } else { + headers["Date"] = gmtime_fmt(time(NULL), c_str); + } + DumpHeaders(str); + } + str += "\r\n"; + if (is_dump_body) { + DumpBody(str); + } + return str; +} + +void HttpResponse::SetRange(long from, long to, long total) { + SetHeader("Content-Range", hv::asprintf("bytes %ld-%ld/%ld", from, to, total)); +} + +bool HttpResponse::GetRange(long& from, long& to, long& total) { + auto iter = headers.find("Content-Range"); + if (iter != headers.end()) { + sscanf(iter->second.c_str(), "bytes %ld-%ld/%ld", &from, &to, &total); + return true; + } + from = to = total = 0; + return false; +} diff --git a/external/libhv/libhv-1.3.2/http/HttpMessage.h b/external/libhv/libhv-1.3.2/http/HttpMessage.h new file mode 100644 index 0000000..cc779c3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/HttpMessage.h @@ -0,0 +1,513 @@ +#ifndef HV_HTTP_MESSAGE_H_ +#define HV_HTTP_MESSAGE_H_ + +/* + * @class HttpMessage + * HttpRequest extends HttpMessage + * HttpResponse extends HttpMessage + * + * @member + * request-line: GET / HTTP/1.1\r\n => method path + * response-line: HTTP/1.1 200 OK\r\n => status_code + * headers, cookies + * body + * + * content, content_length, content_type + * json, form, kv + * + * @function + * Content, ContentLength, ContentType + * ParseUrl, ParseBody + * DumpUrl, DumpHeaders, DumpBody, Dump + * GetHeader, GetParam, GetJson, GetFormData, GetUrlEncoded + * SetHeader, SetParam, SetBody, SetFormData, SetUrlEncoded + * Get, Set + * GetString, GetBool, GetInt, GetFloat + * String, Data, Json, File, FormFile + * + * @example + * examples/http_server_test.cpp + * examples/http_client_test.cpp + * examples/httpd + * + */ + +#include +#include +#include +#include + +#include "hexport.h" +#include "hbase.h" +#include "hstring.h" +#include "hfile.h" +#include "hpath.h" + +#include "httpdef.h" +#include "http_content.h" + +namespace hv { + +struct NetAddr { + std::string ip; + int port; + + std::string ipport() { + return hv::asprintf("%s:%d", ip.c_str(), port); + } +}; + +} + +// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie +// Cookie: sessionid=1; domain=.example.com; path=/; max-age=86400; secure; httponly +struct HV_EXPORT HttpCookie { + std::string name; + std::string value; + std::string domain; + std::string path; + std::string expires; + int max_age; + bool secure; + bool httponly; + enum SameSite { + Default, + Strict, + Lax, + None + } samesite; + enum Priority { + NotSet, + Low, + Medium, + High, + } priority; + hv::KeyValue kv; // for multiple names + + HttpCookie(); + + void init(); + void reset(); + + bool parse(const std::string& str); + std::string dump() const; +}; + +typedef std::map http_headers; +typedef std::vector http_cookies; +typedef std::string http_body; + +HV_EXPORT extern http_headers DefaultHeaders; +HV_EXPORT extern http_body NoBody; +HV_EXPORT extern HttpCookie NoCookie; + +class HV_EXPORT HttpMessage { +public: + static char s_date[32]; + int type; + unsigned short http_major; + unsigned short http_minor; + + http_headers headers; + http_cookies cookies; + http_body body; + + // http_cb + std::function http_cb; + + // structured content + void* content; // DATA_NO_COPY + size_t content_length; + http_content_type content_type; +#ifndef WITHOUT_HTTP_CONTENT + hv::Json json; // APPLICATION_JSON + hv::MultiPart form; // MULTIPART_FORM_DATA + hv::KeyValue kv; // X_WWW_FORM_URLENCODED + + // T=[bool, int, int64_t, float, double] + template + T Get(const char* key, T defvalue = 0); + + std::string GetString(const char* key, const std::string& = ""); + bool GetBool(const char* key, bool defvalue = 0); + int64_t GetInt(const char* key, int64_t defvalue = 0); + double GetFloat(const char* key, double defvalue = 0); + + template + void Set(const char* key, const T& value) { + switch (ContentType()) { + case APPLICATION_JSON: + json[key] = value; + break; + case MULTIPART_FORM_DATA: + form[key] = hv::FormData(value); + break; + case X_WWW_FORM_URLENCODED: + kv[key] = hv::to_string(value); + break; + default: + break; + } + } + + /* + * @usage https://github.com/nlohmann/json + * + * null: Json(nullptr); + * boolean: Json(true); + * number: Json(123); + * string: Json("hello"); + * object: Json(std::map); + * Json(hv::Json::object({ + {"k1", "v1"}, + {"k2", "v2"} + })); + * array: Json(std::vector); + Json(hv::Json::array( + {1, 2, 3} + )); + */ + // Content-Type: application/json + template + int Json(const T& t) { + content_type = APPLICATION_JSON; + hv::Json j(t); + body = j.dump(2); + return 200; + } + const hv::Json& GetJson() { + if (json.empty() && ContentType() == APPLICATION_JSON) { + ParseBody(); + } + return json; + } + + // Content-Type: multipart/form-data + template + void SetFormData(const char* name, const T& t) { + form[name] = hv::FormData(t); + } + void SetFormFile(const char* name, const char* filepath) { + form[name] = hv::FormData(NULL, filepath); + } + int FormFile(const char* name, const char* filepath) { + content_type = MULTIPART_FORM_DATA; + form[name] = hv::FormData(NULL, filepath); + return 200; + } + const hv::MultiPart& GetForm() { + if (form.empty() && ContentType() == MULTIPART_FORM_DATA) { + ParseBody(); + } + return form; + } + std::string GetFormData(const char* name, const std::string& defvalue = hv::empty_string) { + if (form.empty() && ContentType() == MULTIPART_FORM_DATA) { + ParseBody(); + } + auto iter = form.find(name); + return iter == form.end() ? defvalue : iter->second.content; + } + int SaveFormFile(const char* name, const char* path) { + if (ContentType() != MULTIPART_FORM_DATA) { + return HTTP_STATUS_BAD_REQUEST; + } + if (form.empty()) { + ParseBody(); + if (form.empty()) return HTTP_STATUS_BAD_REQUEST; + } + auto iter = form.find(name); + if (iter == form.end()) { + return HTTP_STATUS_BAD_REQUEST; + } + const auto& formdata = iter->second; + if (formdata.content.empty()) { + return HTTP_STATUS_BAD_REQUEST; + } + std::string filepath(path); + if (HPath::isdir(path)) { + filepath = HPath::join(filepath, formdata.filename); + } + HFile file; + if (file.open(filepath.c_str(), "wb") != 0) { + return HTTP_STATUS_INTERNAL_SERVER_ERROR; + } + file.write(formdata.content.data(), formdata.content.size()); + return 200; + } + + // Content-Type: application/x-www-form-urlencoded + template + void SetUrlEncoded(const char* key, const T& t) { + kv[key] = hv::to_string(t); + } + const hv::KeyValue& GetUrlEncoded() { + if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) { + ParseBody(); + } + return kv; + } + std::string GetUrlEncoded(const char* key, const std::string& defvalue = hv::empty_string) { + if (kv.empty() && ContentType() == X_WWW_FORM_URLENCODED) { + ParseBody(); + } + auto iter = kv.find(key); + return iter == kv.end() ? defvalue : iter->second; + } +#endif + + HttpMessage(); + virtual ~HttpMessage(); + + void Init(); + virtual void Reset(); + + // structured-content -> content_type <-> headers["Content-Type"] + void FillContentType(); + // body.size -> content_length <-> headers["Content-Length"] + void FillContentLength(); + + bool IsChunked(); + bool IsKeepAlive(); + bool IsUpgrade(); + + // headers + void SetHeader(const char* key, const std::string& value); + std::string GetHeader(const char* key, const std::string& defvalue = hv::empty_string); + + // cookies + void AddCookie(const HttpCookie& cookie); + const HttpCookie& GetCookie(const std::string& name); + + // body + void SetBody(const std::string& body); + const std::string& Body(); + + // headers -> string + void DumpHeaders(std::string& str); + // structured content -> body + void DumpBody(); + void DumpBody(std::string& str); + // body -> structured content + // @retval 0:succeed + int ParseBody(); + + virtual std::string Dump(bool is_dump_headers, bool is_dump_body); + + void* Content() { + if (content == NULL && body.size() != 0) { + content = (void*)body.data(); + } + return content; + } + + size_t ContentLength() { + if (content_length == 0) { + FillContentLength(); + } + return content_length; + } + + http_content_type ContentType() { + if (content_type == CONTENT_TYPE_NONE) { + FillContentType(); + } + return content_type; + } + void SetContentType(http_content_type type) { + content_type = type; + } + void SetContentType(const char* type) { + content_type = http_content_type_enum(type); + } + void SetContentTypeByFilename(const char* filepath) { + const char* suffix = hv_suffixname(filepath); + if (suffix) { + content_type = http_content_type_enum_by_suffix(suffix); + } + if (content_type == CONTENT_TYPE_NONE || content_type == CONTENT_TYPE_UNDEFINED) { + content_type = APPLICATION_OCTET_STREAM; + } + } + + int String(const std::string& str) { + content_type = TEXT_PLAIN; + body = str; + return 200; + } + + int Data(void* data, int len, bool nocopy = true) { + content_type = APPLICATION_OCTET_STREAM; + if (nocopy) { + content = data; + content_length = len; + } else { + content_length = body.size(); + body.resize(content_length + len); + memcpy((void*)(body.data() + content_length), data, len); + content_length += len; + } + return 200; + } + + int File(const char* filepath) { + HFile file; + if (file.open(filepath, "rb") != 0) { + return HTTP_STATUS_NOT_FOUND; + } + SetContentTypeByFilename(filepath); + file.readall(body); + return 200; + } + + int SaveFile(const char* filepath) { + HFile file; + if (file.open(filepath, "wb") != 0) { + return HTTP_STATUS_NOT_FOUND; + } + file.write(body.data(), body.size()); + return 200; + } +}; + +#define DEFAULT_HTTP_USER_AGENT "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" +#define DEFAULT_HTTP_TIMEOUT 60 // s +#define DEFAULT_HTTP_CONNECT_TIMEOUT 10 // s +#define DEFAULT_HTTP_FAIL_RETRY_COUNT 1 +#define DEFAULT_HTTP_FAIL_RETRY_DELAY 1000 // ms + +class HV_EXPORT HttpRequest : public HttpMessage { +public: + http_method method; + // scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment] + std::string url; + // structured url + std::string scheme; + std::string host; + int port; + std::string path; + hv::QueryParams query_params; + // client_addr + hv::NetAddr client_addr; // for http server save client addr of request + // for HttpClient + uint16_t timeout; // unit: s + uint16_t connect_timeout;// unit: s + uint32_t retry_count; + uint32_t retry_delay; // unit: ms + unsigned redirect: 1; + unsigned proxy : 1; + unsigned cancel : 1; + + HttpRequest(); + + void Init(); + virtual void Reset(); + + virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false); + + // method + void SetMethod(const char* method) { + this->method = http_method_enum(method); + } + const char* Method() { + return http_method_str(method); + } + + // scheme + bool IsHttps() { + return strncmp(scheme.c_str(), "https", 5) == 0 || + strncmp(url.c_str(), "https://", 8) == 0; + } + + // url + void SetUrl(const char* url) { + this->url = url; + } + const std::string& Url() { + return url; + } + // structed url -> url + void DumpUrl(); + // url -> structed url + void ParseUrl(); + + // /path?query#fragment + std::string FullPath() { return path; } + // /path + std::string Path(); + + // ?query_params + template + void SetParam(const char* key, const T& t) { + query_params[key] = hv::to_string(t); + } + std::string GetParam(const char* key, const std::string& defvalue = hv::empty_string) { + auto iter = query_params.find(key); + return iter == query_params.end() ? defvalue : iter->second; + } + + // Host: + std::string Host() { + auto iter = headers.find("Host"); + return iter == headers.end() ? host : iter->second; + } + void FillHost(const char* host, int port = DEFAULT_HTTP_PORT); + void SetHost(const char* host, int port = DEFAULT_HTTP_PORT); + + void SetProxy(const char* host, int port); + bool IsProxy() { return proxy; } + + // Auth + void SetAuth(const std::string& auth); + void SetBasicAuth(const std::string& username, const std::string& password); + void SetBearerTokenAuth(const std::string& token); + + void SetTimeout(int sec) { timeout = sec; } + void SetConnectTimeout(int sec) { connect_timeout = sec; } + + void AllowRedirect(bool on = true) { redirect = on; } + + // NOTE: SetRetry just for AsyncHttpClient + void SetRetry(int count = DEFAULT_HTTP_FAIL_RETRY_COUNT, + int delay = DEFAULT_HTTP_FAIL_RETRY_DELAY) { + retry_count = count; + retry_delay = delay; + } + void Cancel() { cancel = 1; } + bool IsCanceled() { return cancel == 1; } + + // Range: bytes=0-4095 + void SetRange(long from = 0, long to = -1); + bool GetRange(long& from, long& to); +}; + +class HV_EXPORT HttpResponse : public HttpMessage { +public: + http_status status_code; + const char* status_message() { + return http_status_str(status_code); + } + + HttpResponse(); + + void Init(); + virtual void Reset(); + + virtual std::string Dump(bool is_dump_headers = true, bool is_dump_body = false); + + // Content-Range: bytes 0-4095/10240000 + void SetRange(long from, long to, long total); + bool GetRange(long& from, long& to, long& total); + + int Redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) { + status_code = status; + SetHeader("Location", location); + return status_code; + } +}; + +typedef std::shared_ptr HttpRequestPtr; +typedef std::shared_ptr HttpResponsePtr; +typedef std::function HttpResponseCallback; + +#endif // HV_HTTP_MESSAGE_H_ diff --git a/external/libhv/libhv-1.3.2/http/HttpParser.cpp b/external/libhv/libhv-1.3.2/http/HttpParser.cpp new file mode 100644 index 0000000..210bbf6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/HttpParser.cpp @@ -0,0 +1,25 @@ +#include "HttpParser.h" + +#include "Http1Parser.h" +#include "Http2Parser.h" + +HttpParser* HttpParser::New(http_session_type type, http_version version) { + HttpParser* hp = NULL; + if (version == HTTP_V1) { + hp = new Http1Parser(type); + } + else if (version == HTTP_V2) { +#ifdef WITH_NGHTTP2 + hp = new Http2Parser(type); +#else + fprintf(stderr, "Please recompile WITH_NGHTTP2!\n"); +#endif + } + + if (hp) { + hp->version = version; + hp->type = type; + } + + return hp; +} diff --git a/external/libhv/libhv-1.3.2/http/HttpParser.h b/external/libhv/libhv-1.3.2/http/HttpParser.h new file mode 100644 index 0000000..1f9fc2a --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/HttpParser.h @@ -0,0 +1,53 @@ +#ifndef HV_HTTP_PARSER_H_ +#define HV_HTTP_PARSER_H_ + +#include "hexport.h" +#include "HttpMessage.h" + +class HV_EXPORT HttpParser { +public: + http_version version; + http_session_type type; + + static HttpParser* New(http_session_type type = HTTP_CLIENT, http_version version = HTTP_V1); + virtual ~HttpParser() {} + + virtual int GetSendData(char** data, size_t* len) = 0; + virtual int FeedRecvData(const char* data, size_t len) = 0; + + // Http1Parser: http_parser_state + // Http2Parser: http2_session_state + virtual int GetState() = 0; + + // Http1Parser: GetState() != HP_MESSAGE_COMPLETE + // Http2Parser: GetState() == H2_WANT_RECV + virtual bool WantRecv() = 0; + + // Http1Parser: GetState() == HP_MESSAGE_COMPLETE + // Http2Parser: GetState() == H2_WANT_SEND + virtual bool WantSend() = 0; + + // IsComplete: Is recved HttpRequest or HttpResponse complete? + // Http1Parser: GetState() == HP_MESSAGE_COMPLETE + // Http2Parser: (state == H2_RECV_HEADERS || state == H2_RECV_DATA) && stream_closed + virtual bool IsComplete() = 0; + + virtual bool IsEof() { return false; } + + // client + // SubmitRequest -> while(GetSendData) {send} -> InitResponse -> do {recv -> FeedRecvData} while(WantRecv) + virtual int SubmitRequest(HttpRequest* req) = 0; + virtual int InitResponse(HttpResponse* res) = 0; + + // server + // InitRequest -> do {recv -> FeedRecvData} while(WantRecv) -> SubmitResponse -> while(GetSendData) {send} + virtual int InitRequest(HttpRequest* req) = 0; + virtual int SubmitResponse(HttpResponse* res) = 0; + + virtual int GetError() = 0; + virtual const char* StrError(int error) = 0; +}; + +typedef std::shared_ptr HttpParserPtr; + +#endif // HV_HTTP_PARSER_H_ diff --git a/external/libhv/libhv-1.3.2/http/README.md b/external/libhv/libhv-1.3.2/http/README.md new file mode 100644 index 0000000..2ffd401 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/README.md @@ -0,0 +1,26 @@ +## 目录结构 + +``` +. +├── client +│   ├── HttpClient.h http客户端对外头文件 +│   ├── requests.h 模拟python requests api +│   └── axios.h 模拟nodejs axios api +├── httpdef.h http定义 +├── http2def.h http2定义 +├── grpcdef.h grpc定义 +├── HttpParser.h http解析基类 +├── Http1Parser.h http1解析类 +├── Http2Parser.h http2解析类 +├── HttpMessage.h http请求响应类 +├── http_content.h http Content-Type +├── http_parser.h http1解析实现 +├── multipart_parser.h multipart解析 +└── server + ├── HttpServer.h http服务端对外头文件 + ├── HttpHandler.h http处理类 + ├── FileCache.h 文件缓存类 + ├── http_page.h http页面构造 + └── HttpService.h http业务类 (包括api service、web service、indexof service) + +``` diff --git a/external/libhv/libhv-1.3.2/http/WebSocketChannel.cpp b/external/libhv/libhv-1.3.2/http/WebSocketChannel.cpp new file mode 100644 index 0000000..da233db --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/WebSocketChannel.cpp @@ -0,0 +1,81 @@ +#include "WebSocketChannel.h" + +namespace hv { + +int WebSocketChannel::send(const char* buf, int len, enum ws_opcode opcode /* = WS_OPCODE_BINARY */, bool fin /* = true */) { + int fragment = 0xFFFF; // 65535 + if (len > fragment) { + return send(buf, len, fragment, opcode); + } + std::lock_guard locker(mutex_); + return sendFrame(buf, len, opcode, fin); +} + +/* + * websocket fragment + * lock -> + * sendFrame(p, fragment, opcode, false) -> + * sendFrame(p, fragment, WS_OPCODE_CONTINUE, false) -> + * ... -> + * sendFrame(p, remain, WS_OPCODE_CONTINUE, true) + * unlock + * + */ +int WebSocketChannel::send(const char* buf, int len, int fragment, enum ws_opcode opcode /* = WS_OPCODE_BINARY */) { + std::lock_guard locker(mutex_); + if (len <= fragment) { + return sendFrame(buf, len, opcode, true); + } + + // first fragment + int nsend = sendFrame(buf, fragment, opcode, false); + if (nsend < 0) return nsend; + + const char* p = buf + fragment; + int remain = len - fragment; + while (remain > fragment) { + nsend = sendFrame(p, fragment, WS_OPCODE_CONTINUE, false); + if (nsend < 0) return nsend; + p += fragment; + remain -= fragment; + } + + // last fragment + nsend = sendFrame(p, remain, WS_OPCODE_CONTINUE, true); + if (nsend < 0) return nsend; + + return len; +} + +int WebSocketChannel::sendPing() { + std::lock_guard locker(mutex_); + if (type == WS_CLIENT) { + return write(WS_CLIENT_PING_FRAME, WS_CLIENT_MIN_FRAME_SIZE); + } + return write(WS_SERVER_PING_FRAME, WS_SERVER_MIN_FRAME_SIZE); +} + +int WebSocketChannel::sendPong() { + std::lock_guard locker(mutex_); + if (type == WS_CLIENT) { + return write(WS_CLIENT_PONG_FRAME, WS_CLIENT_MIN_FRAME_SIZE); + } + return write(WS_SERVER_PONG_FRAME, WS_SERVER_MIN_FRAME_SIZE); +} + +int WebSocketChannel::sendFrame(const char* buf, int len, enum ws_opcode opcode /* = WS_OPCODE_BINARY */, bool fin /* = true */) { + bool has_mask = false; + char mask[4] = {0}; + if (type == WS_CLIENT) { + *(int*)mask = rand(); + has_mask = true; + } + int frame_size = ws_calc_frame_size(len, has_mask); + if (sendbuf_.len < (size_t)frame_size) { + sendbuf_.resize(ceil2e(frame_size)); + } + ws_build_frame(sendbuf_.base, buf, len, mask, has_mask, opcode, fin); + return write(sendbuf_.base, frame_size); +} + +} diff --git a/external/libhv/libhv-1.3.2/http/WebSocketChannel.h b/external/libhv/libhv-1.3.2/http/WebSocketChannel.h new file mode 100644 index 0000000..b0a8a97 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/WebSocketChannel.h @@ -0,0 +1,55 @@ +#ifndef HV_WEBSOCKET_CHANNEL_H_ +#define HV_WEBSOCKET_CHANNEL_H_ + +#include + +#include "Channel.h" + +#include "wsdef.h" +#include "hmath.h" + +namespace hv { + +class HV_EXPORT WebSocketChannel : public SocketChannel { +public: + ws_session_type type; + WebSocketChannel(hio_t* io, ws_session_type type = WS_CLIENT) + : SocketChannel(io) + , type(type) + , opcode(WS_OPCODE_CLOSE) + {} + ~WebSocketChannel() {} + + // isConnected, send, close + + int send(const std::string& msg, enum ws_opcode opcode = WS_OPCODE_TEXT, bool fin = true) { + return send(msg.c_str(), msg.size(), opcode, fin); + } + + int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); + + // websocket fragment + int send(const char* buf, int len, int fragment, enum ws_opcode opcode = WS_OPCODE_BINARY); + + int sendPing(); + int sendPong(); + + int close() { + return SocketChannel::close(type == WS_SERVER); + } + +protected: + int sendFrame(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY, bool fin = true); + +public: + enum ws_opcode opcode; +private: + Buffer sendbuf_; + std::mutex mutex_; +}; + +} + +typedef std::shared_ptr WebSocketChannelPtr; + +#endif // HV_WEBSOCKET_CHANNEL_H_ diff --git a/external/libhv/libhv-1.3.2/http/WebSocketParser.cpp b/external/libhv/libhv-1.3.2/http/WebSocketParser.cpp new file mode 100644 index 0000000..e655a56 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/WebSocketParser.cpp @@ -0,0 +1,75 @@ +#include "WebSocketParser.h" + +#include "websocket_parser.h" +#include "hdef.h" + +#define MAX_PAYLOAD_LENGTH (1 << 24) // 16M + +static int on_frame_header(websocket_parser* parser) { + WebSocketParser* wp = (WebSocketParser*)parser->data; + int opcode = parser->flags & WS_OP_MASK; + // printf("on_frame_header opcode=%d\n", opcode); + if (opcode != WS_OP_CONTINUE) { + wp->opcode = opcode; + } + int length = parser->length; + int reserve_length = MIN(length + 1, MAX_PAYLOAD_LENGTH); + if (reserve_length > wp->message.capacity()) { + wp->message.reserve(reserve_length); + } + if (wp->state == WS_FRAME_BEGIN || + wp->state == WS_FRAME_FIN) { + wp->message.clear(); + } + wp->state = WS_FRAME_HEADER; + return 0; +} + +static int on_frame_body(websocket_parser* parser, const char * at, size_t length) { + // printf("on_frame_body length=%d\n", (int)length); + WebSocketParser* wp = (WebSocketParser*)parser->data; + wp->state = WS_FRAME_BODY; + if (wp->parser->flags & WS_HAS_MASK) { + websocket_parser_decode((char*)at, at, length, wp->parser); + } + wp->message.append(at, length); + return 0; +} + +static int on_frame_end(websocket_parser* parser) { + // printf("on_frame_end\n"); + WebSocketParser* wp = (WebSocketParser*)parser->data; + wp->state = WS_FRAME_END; + if (wp->parser->flags & WS_FIN) { + wp->state = WS_FRAME_FIN; + if (wp->onMessage) { + wp->onMessage(wp->opcode, wp->message); + } + } + return 0; +} + +static websocket_parser_settings cbs = { + on_frame_header, + on_frame_body, + on_frame_end +}; + +WebSocketParser::WebSocketParser() { + parser = (websocket_parser*)malloc(sizeof(websocket_parser)); + websocket_parser_init(parser); + parser->data = this; + state = WS_FRAME_BEGIN; + opcode = WS_OP_CLOSE; +} + +WebSocketParser::~WebSocketParser() { + if (parser) { + free(parser); + parser = NULL; + } +} + +int WebSocketParser::FeedRecvData(const char* data, size_t len) { + return websocket_parser_execute(parser, &cbs, data, len); +} diff --git a/external/libhv/libhv-1.3.2/http/WebSocketParser.h b/external/libhv/libhv-1.3.2/http/WebSocketParser.h new file mode 100644 index 0000000..c551550 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/WebSocketParser.h @@ -0,0 +1,35 @@ +#ifndef HV_WEBSOCKET_PARSER_H_ +#define HV_WEBSOCKET_PARSER_H_ + +#include "hexport.h" + +#include +#include +#include + +enum websocket_parser_state { + WS_FRAME_BEGIN, + WS_FRAME_HEADER, + WS_FRAME_BODY, + WS_FRAME_END, + WS_FRAME_FIN, +}; + +struct websocket_parser; +class HV_EXPORT WebSocketParser { +public: + websocket_parser* parser; + websocket_parser_state state; + int opcode; + std::string message; + std::function onMessage; + + WebSocketParser(); + ~WebSocketParser(); + + int FeedRecvData(const char* data, size_t len); +}; + +typedef std::shared_ptr WebSocketParserPtr; + +#endif // HV_WEBSOCKET_PARSER_H_ diff --git a/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.cpp b/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.cpp new file mode 100644 index 0000000..29dab69 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.cpp @@ -0,0 +1,212 @@ +#include "AsyncHttpClient.h" + +namespace hv { + +// createsocket => startConnect => +// onconnect => sendRequest => startRead => +// onread => HttpParser => resp_cb +int AsyncHttpClient::doTask(const HttpClientTaskPtr& task) { + const HttpRequestPtr& req = task->req; + if (req->cancel) { + return -1; + } + + // queueInLoop timeout? + uint64_t now_hrtime = hloop_now_hrtime(EventLoopThread::hloop()); + int elapsed_ms = (now_hrtime - task->start_time) / 1000; + int timeout_ms = req->timeout * 1000; + if (timeout_ms > 0 && elapsed_ms >= timeout_ms) { + hlogw("%s queueInLoop timeout!", req->url.c_str()); + return -10; + } + + req->ParseUrl(); + sockaddr_u peeraddr; + memset(&peeraddr, 0, sizeof(peeraddr)); + const char* host = req->host.c_str(); + int ret = sockaddr_set_ipport(&peeraddr, host, req->port); + if (ret != 0) { + hloge("unknown host %s", host); + return -20; + } + + int connfd = -1; + // first get from conn_pools + char strAddr[SOCKADDR_STRLEN] = {0}; + SOCKADDR_STR(&peeraddr, strAddr); + auto iter = conn_pools.find(strAddr); + if (iter != conn_pools.end()) { + // hlogd("get from conn_pools"); + iter->second.get(connfd); + } + + if (connfd < 0) { + // create socket + connfd = socket(peeraddr.sa.sa_family, SOCK_STREAM, 0); + if (connfd < 0) { + perror("socket"); + return -30; + } + hio_t* connio = hio_get(EventLoopThread::hloop(), connfd); + assert(connio != NULL); + hio_set_peeraddr(connio, &peeraddr.sa, sockaddr_len(&peeraddr)); + addChannel(connio); + // https + if (req->IsHttps() && !req->IsProxy()) { + hio_enable_ssl(connio); + if (!is_ipaddr(host)) { + hio_set_hostname(connio, host); + } + } + } + + const SocketChannelPtr& channel = getChannel(connfd); + assert(channel != NULL); + HttpClientContext* ctx = channel->getContext(); + ctx->task = task; + channel->onconnect = [&channel]() { + sendRequest(channel); + }; + channel->onread = [this, &channel](Buffer* buf) { + HttpClientContext* ctx = channel->getContext(); + if (ctx->task == NULL) return; + if (ctx->task->req->cancel) { + channel->close(); + return; + } + const char* data = (const char*)buf->data(); + int len = buf->size(); + int nparse = ctx->parser->FeedRecvData(data, len); + if (nparse != len) { + ctx->errorCallback(); + channel->close(); + return; + } + if (ctx->parser->IsComplete()) { + auto& req = ctx->task->req; + auto& resp = ctx->resp; + bool keepalive = req->IsKeepAlive() && resp->IsKeepAlive(); + if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) { + std::string location = resp->headers["Location"]; + if (!location.empty()) { + hlogi("redirect %s => %s", req->url.c_str(), location.c_str()); + req->url = location; + req->ParseUrl(); + req->headers["Host"] = req->host; + resp->Reset(); + send(ctx->task); + // NOTE: detatch from original channel->context + ctx->cancelTask(); + } + } else { + ctx->successCallback(); + } + if (keepalive) { + // NOTE: add into conn_pools to reuse + // hlogd("add into conn_pools"); + conn_pools[channel->peeraddr()].add(channel->fd()); + } else { + channel->close(); + } + } + }; + channel->onclose = [this, &channel]() { + HttpClientContext* ctx = channel->getContext(); + // NOTE: remove from conn_pools + // hlogd("remove from conn_pools"); + auto iter = conn_pools.find(channel->peeraddr()); + if (iter != conn_pools.end()) { + iter->second.remove(channel->fd()); + } + + const HttpClientTaskPtr& task = ctx->task; + if (task) { + if (ctx->parser && + ctx->parser->IsEof()) { + ctx->successCallback(); + } + else if (task->req && + task->req->cancel == 0 && + task->req->retry_count-- > 0) { + if (task->req->retry_delay > 0) { + // try again after delay + setTimeout(task->req->retry_delay, [this, task](TimerID timerID){ + hlogi("retry %s %s", http_method_str(task->req->method), task->req->url.c_str()); + sendInLoop(task); + }); + } else { + send(task); + } + } + else { + ctx->errorCallback(); + } + } + + removeChannel(channel); + }; + + // timer + if (timeout_ms > 0) { + ctx->timerID = setTimeout(timeout_ms - elapsed_ms, [&channel](TimerID timerID){ + HttpClientContext* ctx = channel->getContext(); + if (ctx && ctx->task) { + hlogw("%s timeout!", ctx->task->req->url.c_str()); + } + if (channel) { + channel->close(); + } + }); + } + + if (channel->isConnected()) { + // sendRequest + sendRequest(channel); + } else { + // startConnect + if (req->connect_timeout > 0) { + channel->setConnectTimeout(req->connect_timeout * 1000); + } + channel->startConnect(); + } + + return 0; +} + +// InitResponse => SubmitRequest => while(GetSendData) write => startRead +int AsyncHttpClient::sendRequest(const SocketChannelPtr& channel) { + HttpClientContext* ctx = (HttpClientContext*)channel->context(); + assert(ctx != NULL && ctx->task != NULL); + if (ctx->resp == NULL) { + ctx->resp = std::make_shared(); + } + HttpRequest* req = ctx->task->req.get(); + HttpResponse* resp = ctx->resp.get(); + assert(req != NULL && resp != NULL); + if (req->http_cb) resp->http_cb = std::move(req->http_cb); + + if (ctx->parser == NULL) { + ctx->parser.reset(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major)); + } + ctx->parser->InitResponse(resp); + ctx->parser->SubmitRequest(req); + + char* data = NULL; + size_t len = 0; + while (ctx->parser->GetSendData(&data, &len)) { + if (req->cancel) { + channel->close(); + return -1; + } + // NOTE: ensure write buffer size is enough + if (len > (1 << 22) /* 4M */) { + channel->setMaxWriteBufsize(len); + } + channel->write(data, len); + } + channel->startRead(); + + return 0; +} + +} diff --git a/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.h b/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.h new file mode 100644 index 0000000..43ce27b --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/AsyncHttpClient.h @@ -0,0 +1,174 @@ +#ifndef HV_ASYNC_HTTP_CLIENT_H_ +#define HV_ASYNC_HTTP_CLIENT_H_ + +#include +#include + +#include "EventLoopThread.h" +#include "Channel.h" + +#include "HttpMessage.h" +#include "HttpParser.h" + +namespace hv { + +template +class ConnPool { +public: + int size() { + return conns_.size(); + } + + bool get(Conn& conn) { + if (conns_.empty()) return false; + conn = conns_.front(); + conns_.pop_front(); + return true; + } + + bool add(const Conn& conn) { + conns_.push_back(conn); + return true; + } + + bool remove(const Conn& conn) { + auto iter = conns_.begin(); + while (iter != conns_.end()) { + if (*iter == conn) { + iter = conns_.erase(iter); + return true; + } else { + ++iter; + } + } + return false; + } + +private: + std::list conns_; +}; + +struct HttpClientTask { + HttpRequestPtr req; + HttpResponseCallback cb; + uint64_t start_time; +}; +typedef std::shared_ptr HttpClientTaskPtr; + +struct HttpClientContext { + HttpClientTaskPtr task; + + HttpResponsePtr resp; + HttpParserPtr parser; + TimerID timerID; + + HttpClientContext() { + timerID = INVALID_TIMER_ID; + } + + ~HttpClientContext() { + cancelTimer(); + } + + void cancelTimer() { + if (timerID != INVALID_TIMER_ID) { + killTimer(timerID); + timerID = INVALID_TIMER_ID; + } + } + + void cancelTask() { + cancelTimer(); + task = NULL; + } + + void callback() { + cancelTimer(); + if (task && task->cb) { + task->cb(resp); + } + // NOTE: task done + task = NULL; + } + + void successCallback() { + callback(); + resp = NULL; + } + + void errorCallback() { + resp = NULL; + callback(); + } +}; + +class HV_EXPORT AsyncHttpClient : private EventLoopThread { +public: + AsyncHttpClient(EventLoopPtr loop = NULL) : EventLoopThread(loop) { + if (loop == NULL) { + EventLoopThread::start(true); + } + } + ~AsyncHttpClient() { + EventLoopThread::stop(true); + } + + // thread-safe + int send(const HttpRequestPtr& req, HttpResponseCallback resp_cb) { + auto task = std::make_shared(); + task->req = req; + task->cb = std::move(resp_cb); + task->start_time = hloop_now_hrtime(EventLoopThread::hloop()); + if (req->retry_count > 0 && req->retry_delay > 0) { + req->retry_count = MIN(req->retry_count, req->timeout * 1000 / req->retry_delay - 1); + } + return send(task); + } + + int send(const HttpClientTaskPtr& task) { + EventLoopThread::loop()->queueInLoop(std::bind(&AsyncHttpClient::sendInLoop, this, task)); + return 0; + } + +protected: + void sendInLoop(HttpClientTaskPtr task) { + int err = doTask(task); + if (err != 0 && task->cb) { + task->cb(NULL); + } + } + int doTask(const HttpClientTaskPtr& task); + + static int sendRequest(const SocketChannelPtr& channel); + + // channel + const SocketChannelPtr& getChannel(int fd) { + return channels[fd]; + // return fd < channels.capacity() ? channels[fd] : NULL; + } + + const SocketChannelPtr& addChannel(hio_t* io) { + auto channel = std::make_shared(io); + channel->newContext(); + int fd = channel->fd(); + channels[fd] = channel; + return channels[fd]; + } + + void removeChannel(const SocketChannelPtr& channel) { + channel->deleteContext(); + int fd = channel->fd(); + channels.erase(fd); + } + +private: + // NOTE: just one loop thread, no need mutex. + // fd => SocketChannelPtr + std::map channels; + // peeraddr => ConnPool + std::map> conn_pools; +}; + +} + +#endif // HV_ASYNC_HTTP_CLIENT_H_ diff --git a/external/libhv/libhv-1.3.2/http/client/HttpClient.cpp b/external/libhv/libhv-1.3.2/http/client/HttpClient.cpp new file mode 100644 index 0000000..0960b68 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/HttpClient.cpp @@ -0,0 +1,733 @@ +#include "HttpClient.h" + +#include + +#ifdef WITH_CURL +#include "curl/curl.h" +#endif + +#include "herr.h" +#include "hlog.h" +#include "htime.h" +#include "hstring.h" +#include "hsocket.h" +#include "hssl.h" +#include "HttpParser.h" + +// for async +#include "AsyncHttpClient.h" + +using namespace hv; + +struct http_client_s { + std::string host; + int port; + int https; + int timeout; // s + http_headers headers; + // http_proxy + std::string http_proxy_host; + int http_proxy_port; + // https_proxy + std::string https_proxy_host; + int https_proxy_port; + // no_proxy + StringList no_proxy_hosts; +//private: +#ifdef WITH_CURL + CURL* curl; +#endif + // for sync + int fd; + unsigned int keepalive_requests; + hssl_t ssl; + hssl_ctx_t ssl_ctx; + bool alloced_ssl_ctx; + HttpParserPtr parser; + // for async + std::mutex mutex_; + std::shared_ptr async_client_; + + http_client_s() { + host = LOCALHOST; + port = DEFAULT_HTTP_PORT; + https = 0; + timeout = DEFAULT_HTTP_TIMEOUT; + http_proxy_port = DEFAULT_HTTP_PORT; + https_proxy_port = DEFAULT_HTTP_PORT; +#ifdef WITH_CURL + curl = NULL; +#endif + fd = -1; + keepalive_requests = 0; + ssl = NULL; + ssl_ctx = NULL; + alloced_ssl_ctx = false; + } + + ~http_client_s() { + Close(); + if (ssl_ctx && alloced_ssl_ctx) { + hssl_ctx_free(ssl_ctx); + ssl_ctx = NULL; + } + } + + void Close() { +#ifdef WITH_CURL + if (curl) { + curl_easy_cleanup(curl); + curl = NULL; + } +#endif + if (ssl) { + hssl_free(ssl); + ssl = NULL; + } + SAFE_CLOSESOCKET(fd); + } +}; + +http_client_t* http_client_new(const char* host, int port, int https) { + http_client_t* cli = new http_client_t; + if (host) cli->host = host; + cli->port = port; + cli->https = https; + cli->headers["Connection"] = "keep-alive"; + return cli; +} + +int http_client_del(http_client_t* cli) { + if (cli == NULL) return 0; + delete cli; + return 0; +} + +int http_client_set_timeout(http_client_t* cli, int timeout) { + cli->timeout = timeout; + return 0; +} + +int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx) { + cli->ssl_ctx = ssl_ctx; + return 0; +} + +int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt) { + opt->endpoint = HSSL_CLIENT; + hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); + if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; + cli->alloced_ssl_ctx = true; + return http_client_set_ssl_ctx(cli, ssl_ctx); +} + +int http_client_clear_headers(http_client_t* cli) { + cli->headers.clear(); + return 0; +} + +int http_client_set_header(http_client_t* cli, const char* key, const char* value) { + cli->headers[key] = value; + return 0; +} + +int http_client_del_header(http_client_t* cli, const char* key) { + auto iter = cli->headers.find(key); + if (iter != cli->headers.end()) { + cli->headers.erase(iter); + } + return 0; +} + +const char* http_client_get_header(http_client_t* cli, const char* key) { + auto iter = cli->headers.find(key); + if (iter != cli->headers.end()) { + return iter->second.c_str(); + } + return NULL; +} + +int http_client_set_http_proxy(http_client_t* cli, const char* host, int port) { + cli->http_proxy_host = host; + cli->http_proxy_port = port; + return 0; +} + +int http_client_set_https_proxy(http_client_t* cli, const char* host, int port) { + cli->https_proxy_host = host; + cli->https_proxy_port = port; + return 0; +} + +int http_client_add_no_proxy(http_client_t* cli, const char* host) { + cli->no_proxy_hosts.push_back(host); + return 0; +} + +static int http_client_make_request(http_client_t* cli, HttpRequest* req) { + if (req->url.empty() || *req->url.c_str() == '/') { + req->scheme = cli->https ? "https" : "http"; + req->host = cli->host; + req->port = cli->port; + } + req->ParseUrl(); + + bool https = req->IsHttps(); + bool use_proxy = https ? (!cli->https_proxy_host.empty()) : (!cli->http_proxy_host.empty()); + if (use_proxy) { + if (req->host == "127.0.0.1" || req->host == "localhost") { + use_proxy = false; + } + } + if (use_proxy) { + for (const auto& host : cli->no_proxy_hosts) { + if (req->host == host) { + use_proxy = false; + break; + } + } + } + if (use_proxy) { + req->SetProxy(https ? cli->https_proxy_host.c_str() : cli->http_proxy_host.c_str(), + https ? cli->https_proxy_port : cli->http_proxy_port); + } + + if (req->timeout == 0) { + req->timeout = cli->timeout; + } + + for (const auto& pair : cli->headers) { + if (req->headers.find(pair.first) == req->headers.end()) { + req->headers.insert(pair); + } + } + + return 0; +} + +int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout) { + cli->Close(); + int blocktime = DEFAULT_CONNECT_TIMEOUT; + if (timeout > 0) { + blocktime = MIN(timeout*1000, blocktime); + } + int connfd = ConnectTimeout(host, port, blocktime); + if (connfd < 0) { + hloge("connect %s:%d failed!", host, port); + return connfd; + } + tcp_nodelay(connfd, 1); + + if (https && cli->ssl == NULL) { + // cli->ssl_ctx > g_ssl_ctx > hssl_ctx_new + hssl_ctx_t ssl_ctx = NULL; + if (cli->ssl_ctx) { + ssl_ctx = cli->ssl_ctx; + } else if (g_ssl_ctx) { + ssl_ctx = g_ssl_ctx; + } else { + cli->ssl_ctx = ssl_ctx = hssl_ctx_new(NULL); + cli->alloced_ssl_ctx = true; + } + if (ssl_ctx == NULL) { + closesocket(connfd); + return NABS(ERR_NEW_SSL_CTX); + } + cli->ssl = hssl_new(ssl_ctx, connfd); + if (cli->ssl == NULL) { + closesocket(connfd); + return NABS(ERR_NEW_SSL); + } + if (!is_ipaddr(host)) { + hssl_set_sni_hostname(cli->ssl, host); + } + so_rcvtimeo(connfd, blocktime); + int ret = hssl_connect(cli->ssl); + if (ret != 0) { + fprintf(stderr, "* ssl handshake failed: %d\n", ret); + hloge("ssl handshake failed: %d", ret); + hssl_free(cli->ssl); + cli->ssl = NULL; + closesocket(connfd); + return NABS(ret); + } + } + + cli->fd = connfd; + cli->keepalive_requests = 0; + return connfd; +} + +int http_client_close(http_client_t* cli) { + if (cli == NULL) return 0; + cli->Close(); + return 0; +} + +int http_client_send_data(http_client_t* cli, const char* data, int size) { + if (!cli || !data || size <= 0) return -1; + + if (cli->ssl) { + return hssl_write(cli->ssl, data, size); + } + + return send(cli->fd, data, size, 0); +} + +int http_client_recv_data(http_client_t* cli, char* data, int size) { + if (!cli || !data || size <= 0) return -1; + + if (cli->ssl) { + return hssl_read(cli->ssl, data, size); + } + + return recv(cli->fd, data, size, 0); +} + +static int http_client_exec(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { + // connect -> send -> recv -> http_parser + int err = 0; + int connfd = cli->fd; + bool https = req->IsHttps() && !req->IsProxy(); + bool keepalive = true; + + time_t connect_timeout = MIN(req->connect_timeout, req->timeout); + time_t timeout_ms = req->timeout * 1000; + time_t start_time = gettick_ms(); + time_t cur_time = start_time, left_time = INFINITE; + +#define CHECK_TIMEOUT \ + do { \ + if (timeout_ms > 0) { \ + cur_time = gettick_ms(); \ + if (cur_time - start_time >= timeout_ms) { \ + goto timeout; \ + } \ + left_time = timeout_ms - (cur_time - start_time); \ + } \ + } while(0); + + uint32_t retry_count = req->retry_count; + if (cli->keepalive_requests > 0 && retry_count == 0) { + // maybe keep-alive timeout, retry at least once + retry_count = 1; + } + + if (cli->parser == NULL) { + cli->parser = HttpParserPtr(HttpParser::New(HTTP_CLIENT, (http_version)req->http_major)); + if (cli->parser == NULL) { + hloge("New HttpParser failed!"); + return ERR_NULL_POINTER; + } + } + + if (connfd <= 0 || cli->host != req->host || cli->port != req->port) { + cli->host = req->host; + cli->port = req->port; +connect: + connfd = http_client_connect(cli, req->host.c_str(), req->port, https, connect_timeout); + if (connfd < 0) { + return connfd; + } + } + + cli->parser->SubmitRequest(req); + char recvbuf[1024] = {0}; + int total_nsend, nsend, nrecv; + total_nsend = nsend = nrecv = 0; +send: + char* data = NULL; + size_t len = 0; + while (cli->parser->GetSendData(&data, &len)) { + total_nsend = 0; + while (total_nsend < len) { + CHECK_TIMEOUT + if (left_time != INFINITE) { + so_sndtimeo(cli->fd, left_time); + } + if (req->cancel) goto disconnect; + nsend = http_client_send_data(cli, data + total_nsend, len - total_nsend); + if (req->cancel) goto disconnect; + if (nsend <= 0) { + CHECK_TIMEOUT + err = socket_errno(); + if (err == EINTR) continue; + if (retry_count-- > 0 && left_time > req->retry_delay + connect_timeout * 1000) { + err = 0; + if (req->retry_delay > 0) hv_msleep(req->retry_delay); + goto connect; + } + goto disconnect; + } + total_nsend += nsend; + } + } + if (resp == NULL) return 0; + cli->parser->InitResponse(resp); +recv: + do { + CHECK_TIMEOUT + if (left_time != INFINITE) { + so_rcvtimeo(cli->fd, left_time); + } + if (req->cancel) goto disconnect; + nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf)); + if (req->cancel) goto disconnect; + if (nrecv <= 0) { + CHECK_TIMEOUT + err = socket_errno(); + if (err == EINTR) continue; + if (cli->parser->IsEof()) { + err = 0; + goto disconnect; + } + if (retry_count-- > 0 && left_time > req->retry_delay + connect_timeout * 1000) { + err = 0; + if (req->retry_delay > 0) hv_msleep(req->retry_delay); + goto connect; + } + goto disconnect; + } + int nparse = cli->parser->FeedRecvData(recvbuf, nrecv); + if (nparse != nrecv) { + return ERR_PARSE; + } + } while(!cli->parser->IsComplete()); + + keepalive = req->IsKeepAlive() && resp->IsKeepAlive(); + if (keepalive) { + ++cli->keepalive_requests; + } else { + cli->Close(); + } + return 0; +timeout: + err = ERR_TASK_TIMEOUT; +disconnect: + cli->Close(); + return err; +} + +int http_client_send_header(http_client_t* cli, HttpRequest* req) { + if (!cli || !req) return ERR_NULL_POINTER; + + http_client_make_request(cli, req); + + return http_client_exec(cli, req, NULL); +} + +int http_client_recv_response(http_client_t* cli, HttpResponse* resp) { + if (!cli || !resp) return ERR_NULL_POINTER; + if (!cli->parser) { + hloge("Call http_client_send_header first!"); + return ERR_NULL_POINTER; + } + + char recvbuf[1024] = {0}; + cli->parser->InitResponse(resp); + + do { + int nrecv = http_client_recv_data(cli, recvbuf, sizeof(recvbuf)); + if (nrecv <= 0) { + int err = socket_errno(); + if (err == EINTR) continue; + cli->Close(); + return err; + } + int nparse = cli->parser->FeedRecvData(recvbuf, nrecv); + if (nparse != nrecv) { + return ERR_PARSE; + } + } while(!cli->parser->IsComplete()); + + return 0; +} + +#ifdef WITH_CURL +static size_t s_header_cb(char* buf, size_t size, size_t cnt, void* userdata) { + if (buf == NULL || userdata == NULL) return 0; + size_t len = size * cnt; + std::string str(buf, len); + HttpResponse* resp = (HttpResponse*)userdata; + std::string::size_type pos = str.find_first_of(':'); + if (pos == std::string::npos) { + if (strncmp(buf, "HTTP/", 5) == 0) { + // status line + //hlogd("%s", buf); + int http_major = 1, http_minor = 1, status_code = 200; + if (buf[5] == '1') { + // HTTP/1.1 200 OK\r\n + sscanf(buf, "HTTP/%d.%d %d", &http_major, &http_minor, &status_code); + } + else if (buf[5] == '2') { + // HTTP/2 200\r\n + sscanf(buf, "HTTP/%d %d", &http_major, &status_code); + http_minor = 0; + } + resp->http_major = http_major; + resp->http_minor = http_minor; + resp->status_code = (http_status)status_code; + if (resp->http_cb) { + resp->http_cb(resp, HP_MESSAGE_BEGIN, NULL, 0); + } + } + } + else { + // headers + std::string key = trim(str.substr(0, pos)); + std::string value = trim(str.substr(pos+1)); + resp->headers[key] = value; + } + return len; +} + +static size_t s_body_cb(char* buf, size_t size, size_t cnt, void *userdata) { + if (buf == NULL || userdata == NULL) return 0; + size_t len = size * cnt; + HttpMessage* resp = (HttpMessage*)userdata; + if (resp->http_cb) { + if (resp->content == NULL && resp->content_length == 0) { + resp->content = buf; + resp->content_length = len; + resp->http_cb(resp, HP_HEADERS_COMPLETE, NULL, 0); + } + resp->http_cb(resp, HP_BODY, buf, len); + } else { + resp->body.append(buf, len); + } + return len; +} + +static int http_client_exec_curl(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { + if (cli->curl == NULL) { + cli->curl = curl_easy_init(); + } + CURL* curl = cli->curl; + + // proxy + if (req->IsProxy()) { + curl_easy_setopt(curl, CURLOPT_PROXY, req->host.c_str()); + curl_easy_setopt(curl, CURLOPT_PROXYPORT, req->port); + } + + // SSL + if (req->IsHttps()) { + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); + } + + // http2 + if (req->http_major == 2) { +#if LIBCURL_VERSION_NUM < 0x073100 // 7.49.0 + curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_0); +#else + // No Connection: Upgrade + curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, (long)CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE); +#endif + } + + // TCP_NODELAY + curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1); + + // method + curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_method_str(req->method)); + + // url + req->DumpUrl(); + curl_easy_setopt(curl, CURLOPT_URL, req->url.c_str()); + //hlogd("%s %s HTTP/%d.%d", http_method_str(req->method), req->url.c_str(), req->http_major, req->http_minor); + + // headers + req->FillContentType(); + struct curl_slist *headers = NULL; + for (auto& pair : req->headers) { + std::string header = pair.first; + header += ": "; + header += pair.second; + headers = curl_slist_append(headers, header.c_str()); + } + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); + + // body + //struct curl_httppost* httppost = NULL; + //struct curl_httppost* lastpost = NULL; + if (req->body.size() == 0) { + req->DumpBody(); + /* + if (req->body.size() == 0 && + req->content_type == MULTIPART_FORM_DATA) { + for (auto& pair : req->mp) { + if (pair.second.filename.size() != 0) { + curl_formadd(&httppost, &lastpost, + CURLFORM_COPYNAME, pair.first.c_str(), + CURLFORM_FILE, pair.second.filename.c_str(), + CURLFORM_END); + } + else if (pair.second.content.size() != 0) { + curl_formadd(&httppost, &lastpost, + CURLFORM_COPYNAME, pair.first.c_str(), + CURLFORM_COPYCONTENTS, pair.second.content.c_str(), + CURLFORM_END); + } + } + if (httppost) { + curl_easy_setopt(curl, CURLOPT_HTTPPOST, httppost); + } + } + */ + } + if (req->body.size() != 0) { + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, req->body.c_str()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, req->body.size()); + } + + if (req->connect_timeout > 0) { + curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, req->connect_timeout); + } + if (req->timeout > 0) { + curl_easy_setopt(curl, CURLOPT_TIMEOUT, req->timeout); + } + + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, s_body_cb); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, resp); + + curl_easy_setopt(curl, CURLOPT_HEADER, 0); + curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, s_header_cb); + curl_easy_setopt(curl, CURLOPT_HEADERDATA, resp); + + int ret = curl_easy_perform(curl); + /* + if (ret != 0) { + hloge("curl error: %d: %s", ret, curl_easy_strerror((CURLcode)ret)); + } + if (resp->body.length() != 0) { + hlogd("[Response]\n%s", resp->body.c_str()); + } + double total_time, name_time, conn_time, pre_time; + curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time); + curl_easy_getinfo(curl, CURLINFO_NAMELOOKUP_TIME, &name_time); + curl_easy_getinfo(curl, CURLINFO_CONNECT_TIME, &conn_time); + curl_easy_getinfo(curl, CURLINFO_PRETRANSFER_TIME, &pre_time); + hlogd("TIME_INFO: %lf,%lf,%lf,%lf", total_time, name_time, conn_time, pre_time); + */ + + if (headers) { + curl_slist_free_all(headers); + } + /* + if (httppost) { + curl_formfree(httppost); + } + */ + + if (resp->http_cb) { + resp->http_cb(resp, HP_MESSAGE_COMPLETE, NULL, 0); + } + + return ret; +} + +const char* http_client_strerror(int errcode) { + return curl_easy_strerror((CURLcode)errcode); +} + +#else + +const char* http_client_strerror(int errcode) { + return socket_strerror(errcode); +} + +#endif + +static int http_client_redirect(HttpRequest* req, HttpResponse* resp) { + std::string location = resp->headers["Location"]; + if (!location.empty()) { + hlogi("redirect %s => %s", req->url.c_str(), location.c_str()); + req->url = location; + req->ParseUrl(); + req->headers["Host"] = req->host; + resp->Reset(); + return http_client_send(req, resp); + } + return 0; +} + +int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp) { + if (!cli || !req || !resp) return ERR_NULL_POINTER; + + http_client_make_request(cli, req); + + if (req->http_cb) resp->http_cb = std::move(req->http_cb); + +#if WITH_CURL + int ret = http_client_exec_curl(cli, req, resp); +#else + int ret = http_client_exec(cli, req, resp); +#endif + if (ret != 0) return ret; + + // redirect + if (req->redirect && HTTP_STATUS_IS_REDIRECT(resp->status_code)) { + return http_client_redirect(req, resp); + } + return 0; +} + +int http_client_send(HttpRequest* req, HttpResponse* resp) { + if (!req || !resp) return ERR_NULL_POINTER; + + http_client_t cli; + return http_client_send(&cli, req, resp); +} + +// below for async +static int http_client_exec_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) { + if (cli->async_client_ == NULL) { + cli->mutex_.lock(); + if (cli->async_client_ == NULL) { + cli->async_client_ = std::make_shared(); + } + cli->mutex_.unlock(); + } + + return cli->async_client_->send(req, std::move(resp_cb)); +} + +int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb) { + if (!cli || !req) return ERR_NULL_POINTER; + http_client_make_request(cli, req.get()); + return http_client_exec_async(cli, req, std::move(resp_cb)); +} + +static http_client_t* s_async_http_client = NULL; +static void hv_destroy_default_async_http_client() { + hlogi("destory default http async client"); + if (s_async_http_client) { + http_client_del(s_async_http_client); + s_async_http_client = NULL; + } +} +static http_client_t* hv_default_async_http_client() { + static std::mutex s_mutex; + if (s_async_http_client == NULL) { + s_mutex.lock(); + if (s_async_http_client == NULL) { + hlogi("create default http async client"); + s_async_http_client = http_client_new(); + // NOTE: I have No better idea + atexit(hv_destroy_default_async_http_client); + } + s_mutex.unlock(); + } + return s_async_http_client; +} + +int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb) { + if (req == NULL) return ERR_NULL_POINTER; + + if (req->timeout == 0) { + req->timeout = DEFAULT_HTTP_TIMEOUT; + } + + return http_client_exec_async(hv_default_async_http_client(), req, std::move(resp_cb)); +} diff --git a/external/libhv/libhv-1.3.2/http/client/HttpClient.h b/external/libhv/libhv-1.3.2/http/client/HttpClient.h new file mode 100644 index 0000000..4891bb6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/HttpClient.h @@ -0,0 +1,171 @@ +#ifndef HV_HTTP_CLIENT_H_ +#define HV_HTTP_CLIENT_H_ + +#include "hexport.h" +#include "hssl.h" +#include "HttpMessage.h" + +/* +#include + +#include "HttpClient.h" + +int main(int argc, char* argv[]) { + HttpRequest req; + req.method = HTTP_GET; + req.url = "http://www.example.com"; + HttpResponse res; + int ret = http_client_send(&req, &res); + printf("%s\n", req.Dump(true,true).c_str()); + if (ret != 0) { + printf("* Failed:%s:%d\n", http_client_strerror(ret), ret); + } + else { + printf("%s\n", res.Dump(true,true).c_str()); + } + return ret; +} +*/ + +typedef struct http_client_s http_client_t; + +HV_EXPORT http_client_t* http_client_new(const char* host = NULL, int port = DEFAULT_HTTP_PORT, int https = 0); +HV_EXPORT int http_client_del(http_client_t* cli); +HV_EXPORT const char* http_client_strerror(int errcode); + +// timeout: s +HV_EXPORT int http_client_set_timeout(http_client_t* cli, int timeout); + +// SSL/TLS +HV_EXPORT int http_client_set_ssl_ctx(http_client_t* cli, hssl_ctx_t ssl_ctx); +// hssl_ctx_new(opt) -> http_client_set_ssl_ctx +HV_EXPORT int http_client_new_ssl_ctx(http_client_t* cli, hssl_ctx_opt_t* opt); + +// common headers +HV_EXPORT int http_client_clear_headers(http_client_t* cli); +HV_EXPORT int http_client_set_header(http_client_t* cli, const char* key, const char* value); +HV_EXPORT int http_client_del_header(http_client_t* cli, const char* key); +HV_EXPORT const char* http_client_get_header(http_client_t* cli, const char* key); + +// http_proxy +HV_EXPORT int http_client_set_http_proxy(http_client_t* cli, const char* host, int port); +// https_proxy +HV_EXPORT int http_client_set_https_proxy(http_client_t* cli, const char* host, int port); +// no_proxy +HV_EXPORT int http_client_add_no_proxy(http_client_t* cli, const char* host); + +// sync +HV_EXPORT int http_client_send(http_client_t* cli, HttpRequest* req, HttpResponse* resp); + +// async +// Intern will start an EventLoopThread when http_client_send_async first called, +// http_client_del will destroy the thread. +HV_EXPORT int http_client_send_async(http_client_t* cli, HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); + +// top-level api +// http_client_new -> http_client_send -> http_client_del +HV_EXPORT int http_client_send(HttpRequest* req, HttpResponse* resp); +// http_client_send_async(&default_async_client, ...) +HV_EXPORT int http_client_send_async(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL); + +// low-level api +// @retval >=0 connfd, <0 error +HV_EXPORT int http_client_connect(http_client_t* cli, const char* host, int port, int https, int timeout); +HV_EXPORT int http_client_send_header(http_client_t* cli, HttpRequest* req); +HV_EXPORT int http_client_send_data(http_client_t* cli, const char* data, int size); +HV_EXPORT int http_client_recv_data(http_client_t* cli, char* data, int size); +HV_EXPORT int http_client_recv_response(http_client_t* cli, HttpResponse* resp); +HV_EXPORT int http_client_close(http_client_t* cli); + +namespace hv { + +class HttpClient { +public: + HttpClient(const char* host = NULL, int port = DEFAULT_HTTP_PORT, int https = 0) { + _client = http_client_new(host, port, https); + } + + ~HttpClient() { + if (_client) { + http_client_del(_client); + _client = NULL; + } + } + + // timeout: s + int setTimeout(int timeout) { + return http_client_set_timeout(_client, timeout); + } + + // SSL/TLS + int setSslCtx(hssl_ctx_t ssl_ctx) { + return http_client_set_ssl_ctx(_client, ssl_ctx); + } + int newSslCtx(hssl_ctx_opt_t* opt) { + return http_client_new_ssl_ctx(_client, opt); + } + + // headers + int clearHeaders() { + return http_client_clear_headers(_client); + } + int setHeader(const char* key, const char* value) { + return http_client_set_header(_client, key, value); + } + int delHeader(const char* key) { + return http_client_del_header(_client, key); + } + const char* getHeader(const char* key) { + return http_client_get_header(_client, key); + } + + // http_proxy + int setHttpProxy(const char* host, int port) { + return http_client_set_http_proxy(_client, host, port); + } + // https_proxy + int setHttpsProxy(const char* host, int port) { + return http_client_set_https_proxy(_client, host, port); + } + // no_proxy + int addNoProxy(const char* host) { + return http_client_add_no_proxy(_client, host); + } + + // sync + int send(HttpRequest* req, HttpResponse* resp) { + return http_client_send(_client, req, resp); + } + + // async + int sendAsync(HttpRequestPtr req, HttpResponseCallback resp_cb = NULL) { + return http_client_send_async(_client, req, std::move(resp_cb)); + } + + // low-level api + int connect(const char* host, int port = DEFAULT_HTTP_PORT, int https = 0, int timeout = DEFAULT_HTTP_CONNECT_TIMEOUT) { + return http_client_connect(_client, host, port, https, timeout); + } + int sendHeader(HttpRequest* req) { + return http_client_send_header(_client, req); + } + int sendData(const char* data, int size) { + return http_client_send_data(_client, data, size); + } + int recvData(char* data, int size) { + return http_client_recv_data(_client, data, size); + } + int recvResponse(HttpResponse* resp) { + return http_client_recv_response(_client, resp); + } + int close() { + return http_client_close(_client); + } + +private: + http_client_t* _client; +}; + +} + +#endif // HV_HTTP_CLIENT_H_ diff --git a/external/libhv/libhv-1.3.2/http/client/WebSocketClient.cpp b/external/libhv/libhv-1.3.2/http/client/WebSocketClient.cpp new file mode 100644 index 0000000..ff3fc54 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/WebSocketClient.cpp @@ -0,0 +1,216 @@ +#include "WebSocketClient.h" + +#include "base64.h" +#include "hlog.h" + +#define DEFAULT_WS_PING_INTERVAL 3000 // ms + +namespace hv { + +WebSocketClient::WebSocketClient(EventLoopPtr loop) + : TcpClientTmpl(loop) +{ + state = WS_CLOSED; + ping_interval = DEFAULT_WS_PING_INTERVAL; + ping_cnt = 0; +} + +WebSocketClient::~WebSocketClient() { + stop(); +} + +/* + * ParseUrl => createsocket => start => + * TCP::onConnection => websocket_handshake => WS::onopen => + * TCP::onMessage => WebSocketParser => WS::onmessage => + * TCP::onConnection => WS::onclose + */ +int WebSocketClient::open(const char* _url, const http_headers& headers) { + close(); + + // ParseUrl + if (_url) { + if (strncmp(_url, "ws", 2) != 0) { + url = "ws://"; + url += _url; + } else { + url = _url; + } + } + hlogi("%s", url.c_str()); + if (!http_req_) { + http_req_ = std::make_shared(); + } + // ws => http + http_req_->url = "http" + url.substr(2, -1); + http_req_->ParseUrl(); + + int connfd = createsocket(http_req_->port, http_req_->host.c_str()); + if (connfd < 0) { + hloge("createsocket %s:%d return %d!", http_req_->host.c_str(), http_req_->port, connfd); + return connfd; + } + + // wss + bool wss = strncmp(url.c_str(), "wss", 3) == 0; + if (wss) { + withTLS(); + } + + for (auto& header : headers) { + http_req_->headers[header.first] = header.second; + } + + onConnection = [this](const WebSocketChannelPtr& channel) { + if (channel->isConnected()) { + state = CONNECTED; + // websocket_handshake + http_req_->headers["Connection"] = "Upgrade"; + http_req_->headers["Upgrade"] = "websocket"; + if (http_req_->GetHeader(SEC_WEBSOCKET_KEY).empty()) { + // generate SEC_WEBSOCKET_KEY + unsigned char rand_key[16] = {0}; + int *p = (int*)rand_key; + for (int i = 0; i < 4; ++i, ++p) { + *p = rand(); + } + char ws_key[32] = {0}; + hv_base64_encode(rand_key, 16, ws_key); + http_req_->headers[SEC_WEBSOCKET_KEY] = ws_key; + } + if (http_req_->GetHeader(SEC_WEBSOCKET_VERSION).empty()) { + http_req_->headers[SEC_WEBSOCKET_VERSION] = "13"; + } + std::string http_msg = http_req_->Dump(true, true); + // printf("%s", http_msg.c_str()); + // NOTE: not use WebSocketChannel::send + channel->write(http_msg); + state = WS_UPGRADING; + // prepare HttpParser + http_parser_.reset(HttpParser::New(HTTP_CLIENT, HTTP_V1)); + http_resp_ = std::make_shared(); + http_parser_->InitResponse(http_resp_.get()); + } else { + state = WS_CLOSED; + if (onclose) onclose(); + } + }; + onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) { + const char* data = (const char*)buf->data(); + size_t size = buf->size(); + if (state == WS_UPGRADING) { + int nparse = http_parser_->FeedRecvData(data, size); + if (nparse != size && http_parser_->GetError()) { + hloge("http parse error!"); + channel->close(); + return; + } + data += nparse; + size -= nparse; + if (http_parser_->IsComplete()) { + if (http_resp_->status_code != HTTP_STATUS_SWITCHING_PROTOCOLS) { + // printf("websocket response:\n%s\n", http_resp_->Dump(true, true).c_str()); + if (http_req_->redirect && HTTP_STATUS_IS_REDIRECT(http_resp_->status_code)) { + std::string location = http_resp_->headers["Location"]; + if (!location.empty()) { + hlogi("redirect %s => %s", http_req_->url.c_str(), location.c_str()); + std::string ws_url = location; + if (hv::startswith(location, "http")) { + ws_url = hv::replace(location, "http", "ws"); + } + // NOTE: not triggle onclose when redirecting. + channel->onclose = NULL; + open(ws_url.c_str()); + return; + } + } + hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code); + channel->close(); + return; + } + std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY); + char ws_accept[32] = {0}; + ws_encode_key(ws_key.c_str(), ws_accept); + std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT); + if (strcmp(ws_accept, ws_accept2.c_str()) != 0) { + hloge("Sec-WebSocket-Accept not match!"); + channel->close(); + return; + } + ws_parser_ = std::make_shared(); + // websocket_onmessage + ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) { + channel->opcode = (enum ws_opcode)opcode; + switch (opcode) { + case WS_OPCODE_CLOSE: + channel->close(); + break; + case WS_OPCODE_PING: + { + // printf("recv ping\n"); + // printf("send pong\n"); + channel->send(msg, WS_OPCODE_PONG); + break; + } + case WS_OPCODE_PONG: + // printf("recv pong\n"); + ping_cnt = 0; + break; + case WS_OPCODE_TEXT: + case WS_OPCODE_BINARY: + if (onmessage) onmessage(msg); + break; + default: + break; + } + }; + state = WS_OPENED; + // ping + if (ping_interval > 0) { + ping_cnt = 0; + channel->setHeartbeat(ping_interval, [this](){ + auto& channel = this->channel; + if (channel == NULL) return; + if (ping_cnt++ == 3) { + hloge("websocket no pong!"); + channel->close(); + return; + } + // printf("send ping\n"); + channel->sendPing(); + }); + } + if (onopen) onopen(); + } + } + if (state == WS_OPENED && size != 0) { + int nparse = ws_parser_->FeedRecvData(data, size); + if (nparse != size) { + hloge("websocket parse error!"); + channel->close(); + return; + } + } + }; + + state = CONNECTING; + start(); + return 0; +} + +int WebSocketClient::close() { + closesocket(); + state = WS_CLOSED; + return 0; +} + +int WebSocketClient::send(const std::string& msg) { + return send(msg.c_str(), msg.size(), WS_OPCODE_TEXT); +} + +int WebSocketClient::send(const char* buf, int len, enum ws_opcode opcode) { + if (channel == NULL) return -1; + return channel->send(buf, len, opcode); +} + +} diff --git a/external/libhv/libhv-1.3.2/http/client/WebSocketClient.h b/external/libhv/libhv-1.3.2/http/client/WebSocketClient.h new file mode 100644 index 0000000..da0a4af --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/WebSocketClient.h @@ -0,0 +1,71 @@ +#ifndef HV_WEBSOCKET_CLIENT_H_ +#define HV_WEBSOCKET_CLIENT_H_ + +/* + * @demo examples/websocket_client_test.cpp + */ + +#include "hexport.h" + +#include "TcpClient.h" +#include "WebSocketChannel.h" + +#include "HttpParser.h" +#include "WebSocketParser.h" + +namespace hv { + +class HV_EXPORT WebSocketClient : public TcpClientTmpl { +public: + std::string url; + std::function onopen; + std::function onclose; + std::function onmessage; + // PATCH: onmessage not given opcode + enum ws_opcode opcode() { return channel ? channel->opcode : WS_OPCODE_CLOSE; } + + WebSocketClient(EventLoopPtr loop = NULL); + virtual ~WebSocketClient(); + + // url = ws://ip:port/path + // url = wss://ip:port/path + int open(const char* url, const http_headers& headers = DefaultHeaders); + int close(); + int send(const std::string& msg); + int send(const char* buf, int len, enum ws_opcode opcode = WS_OPCODE_BINARY); + + // setConnectTimeout / setPingInterval / setReconnect + void setPingInterval(int ms) { + ping_interval = ms; + } + + // NOTE: call before open + void setHttpRequest(const HttpRequestPtr& req) { + http_req_ = req; + } + + // NOTE: call when onopen + const HttpResponsePtr& getHttpResponse() { + return http_resp_; + } + +private: + enum State { + CONNECTING, + CONNECTED, + WS_UPGRADING, + WS_OPENED, + WS_CLOSED, + } state; + HttpParserPtr http_parser_; + HttpRequestPtr http_req_; + HttpResponsePtr http_resp_; + WebSocketParserPtr ws_parser_; + // ping/pong + int ping_interval; + int ping_cnt; +}; + +} + +#endif // HV_WEBSOCKET_CLIENT_H_ diff --git a/external/libhv/libhv-1.3.2/http/client/axios.h b/external/libhv/libhv-1.3.2/http/client/axios.h new file mode 100644 index 0000000..facd99d --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/axios.h @@ -0,0 +1,193 @@ +#ifndef HV_AXIOS_H_ +#define HV_AXIOS_H_ + +#include "json.hpp" +#include "requests.h" + +/* + * Inspired by js axios + * + * @code + +#include "axios.h" + +int main() { + const char* strReq = R"( + { + "method": "POST", + "url": "http://127.0.0.1:8080/echo", + "timeout": 10, + "params": { + "page_no": "1", + "page_size": "10" + }, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "app_id": "123456", + "app_secret": "abcdefg" + } + } + )"; + + // sync + auto resp = axios::axios(strReq); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + + // async + int finished = 0; + axios::axios(strReq, [&finished](const HttpResponsePtr& resp) { + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%s\n", resp->body.c_str()); + } + finished = 1; + }); + + // wait async finished + while (!finished) hv_sleep(1); + return 0; +} + +**/ + +using nlohmann::json; +using requests::Request; +using requests::Response; +using requests::ResponseCallback; + +namespace axios { + +HV_INLINE Request newRequestFromJson(const json& jreq) { + auto req = std::make_shared(); + // url + if (jreq.contains("url")) { + req->url = jreq["url"]; + } + // params + if (jreq.contains("params")) { + req->query_params = jreq["params"].get(); + } + // headers + if (jreq.contains("headers")) { + req->headers = jreq["headers"].get(); + } + // body/data + const char* body_field = nullptr; + if (jreq.contains("body")) { + body_field = "body"; + } else if (jreq.contains("data")) { + body_field = "data"; + } + if (body_field) { + const json& jbody = jreq[body_field]; + if (jbody.is_object() || jbody.is_array()) { + req->json = jbody; + } else if (jbody.is_string()) { + req->body = jbody; + } + } + // method + if (jreq.contains("method")) { + std::string method = jreq["method"]; + req->method = http_method_enum(method.c_str()); + } else if (body_field) { + req->method = HTTP_POST; + } else { + req->method = HTTP_GET; + } + // timeout + if (jreq.contains("timeout")) { + req->timeout = jreq["timeout"]; + } + return req; +} + +HV_INLINE Request newRequestFromJsonString(const char* req_str) { + return newRequestFromJson(json::parse(req_str)); +} + +// sync +HV_INLINE Response axios(const json& jreq, http_method method = HTTP_GET, const char* url = nullptr) { + auto req = newRequestFromJson(jreq); + if (method != HTTP_GET) { + req->method = method; + } + if (url) { + req->url = url; + } + return req ? requests::request(req) : nullptr; +} + +HV_INLINE Response axios(const char* req_str, http_method method = HTTP_GET, const char* url = nullptr) { + return req_str ? axios(json::parse(req_str), method, url) + : requests::request(method, url); +} + +HV_INLINE Response head(const char* url, const json& jreq) { + return axios(jreq, HTTP_HEAD, url); +} + +HV_INLINE Response head(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_HEAD, url); +} + +HV_INLINE Response get(const char* url, const json& jreq) { + return axios(jreq, HTTP_GET, url); +} + +HV_INLINE Response get(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_GET, url); +} + +HV_INLINE Response post(const char* url, const json& jreq) { + return axios(jreq, HTTP_POST, url); +} + +HV_INLINE Response post(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_POST, url); +} + +HV_INLINE Response put(const char* url, const json& jreq) { + return axios(jreq, HTTP_PUT, url); +} + +HV_INLINE Response put(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_PUT, url); +} + +HV_INLINE Response patch(const char* url, const json& jreq) { + return axios(jreq, HTTP_PATCH, url); +} + +HV_INLINE Response patch(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_PATCH, url); +} + +HV_INLINE Response Delete(const char* url, const json& jreq) { + return axios(jreq, HTTP_DELETE, url); +} + +HV_INLINE Response Delete(const char* url, const char* req_str = nullptr) { + return axios(req_str, HTTP_DELETE, url); +} + +// async +HV_INLINE int axios(const json& jreq, ResponseCallback resp_cb) { + auto req = newRequestFromJson(jreq); + return req ? requests::async(req, std::move(resp_cb)) : -1; +} + +HV_INLINE int axios(const char* req_str, ResponseCallback resp_cb) { + return axios(json::parse(req_str), std::move(resp_cb)); +} + +} + +#endif // HV_AXIOS_H_ diff --git a/external/libhv/libhv-1.3.2/http/client/requests.h b/external/libhv/libhv-1.3.2/http/client/requests.h new file mode 100644 index 0000000..02c26e4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/client/requests.h @@ -0,0 +1,233 @@ +#ifndef HV_REQUESTS_H_ +#define HV_REQUESTS_H_ + +/* + * Inspired by python requests + * + * @code + +#include "requests.h" + +int main() { + auto resp = requests::get("http://127.0.0.1:8080/ping"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + resp = requests::post("http://127.0.0.1:8080/echo", "hello,world!"); + if (resp == NULL) { + printf("request failed!\n"); + } else { + printf("%d %s\r\n", resp->status_code, resp->status_message()); + printf("%s\n", resp->body.c_str()); + } + + return 0; +} + +**/ + +#include +#include "HttpClient.h" + +namespace requests { + +typedef HttpRequestPtr Request; +typedef HttpResponsePtr Response; +typedef HttpResponseCallback ResponseCallback; + +HV_INLINE Response request(Request req) { + auto resp = std::make_shared(); + int ret = http_client_send(req.get(), resp.get()); + return ret ? NULL : resp; +} + +HV_INLINE Response request(http_method method, const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { + auto req = std::make_shared(); + req->method = method; + req->url = url; + if (&body != &NoBody) { + req->body = body; + } + if (&headers != &DefaultHeaders) { + req->headers = headers; + } + return request(req); +} + +HV_INLINE Response head(const char* url, const http_headers& headers = DefaultHeaders) { + return request(HTTP_HEAD, url, NoBody, headers); +} + +HV_INLINE Response get(const char* url, const http_headers& headers = DefaultHeaders) { + return request(HTTP_GET, url, NoBody, headers); +} + +HV_INLINE Response post(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { + return request(HTTP_POST, url, body, headers); +} + +HV_INLINE Response put(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { + return request(HTTP_PUT, url, body, headers); +} + +HV_INLINE Response patch(const char* url, const http_body& body = NoBody, const http_headers& headers = DefaultHeaders) { + return request(HTTP_PATCH, url, body, headers); +} + +// delete is c++ keyword, we have to replace delete with Delete. +HV_INLINE Response Delete(const char* url, const http_headers& headers = DefaultHeaders) { + return request(HTTP_DELETE, url, NoBody, headers); +} + +HV_INLINE int async(Request req, ResponseCallback resp_cb) { + return http_client_send_async(req, std::move(resp_cb)); +} + +// Sample codes for uploading and downloading files +HV_INLINE Response uploadFile(const char* url, const char* filepath, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { + auto req = std::make_shared(); + req->method = method; + req->url = url; + req->timeout = 600; // 10min + if (req->File(filepath) != 200) return NULL; + if (&headers != &DefaultHeaders) { + req->headers = headers; + } + return request(req); +} + +#ifndef WITHOUT_HTTP_CONTENT +HV_INLINE Response uploadFormFile(const char* url, const char* name, const char* filepath, std::map& params = hv::empty_map, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { + auto req = std::make_shared(); + req->method = method; + req->url = url; + req->timeout = 600; // 10min + req->content_type = MULTIPART_FORM_DATA; + req->SetFormFile(name, filepath); + for (auto& param : params) { + req->SetFormData(param.first.c_str(), param.second); + } + if (&headers != &DefaultHeaders) { + req->headers = headers; + } + return request(req); +} +#endif + +typedef std::function upload_progress_cb; +HV_INLINE Response uploadLargeFile(const char* url, const char* filepath, upload_progress_cb progress_cb = NULL, http_method method = HTTP_POST, const http_headers& headers = DefaultHeaders) { + // open file + HFile file; + int ret = file.open(filepath, "rb"); + if (ret != 0) { + return NULL; + } + + hv::HttpClient cli; + auto req = std::make_shared(); + req->method = method; + req->url = url; + req->timeout = 3600; // 1h + if (&headers != &DefaultHeaders) { + req->headers = headers; + } + + // connect + req->ParseUrl(); + int connfd = cli.connect(req->host.c_str(), req->port, req->IsHttps(), req->connect_timeout); + if (connfd < 0) { + return NULL; + } + + // send header + size_t total_bytes = file.size(filepath); + req->SetHeader("Content-Length", hv::to_string(total_bytes)); + ret = cli.sendHeader(req.get()); + if (ret != 0) { + return NULL; + } + + // send file + size_t sended_bytes = 0; + char filebuf[40960]; // 40K + int filebuflen = sizeof(filebuf); + int nread = 0, nsend = 0; + while (sended_bytes < total_bytes) { + nread = file.read(filebuf, filebuflen); + if (nread <= 0) { + return NULL; + } + nsend = cli.sendData(filebuf, nread); + if (nsend != nread) { + return NULL; + } + sended_bytes += nsend; + if (progress_cb) { + progress_cb(sended_bytes, total_bytes); + } + } + + // recv response + auto resp = std::make_shared(); + ret = cli.recvResponse(resp.get()); + if (ret != 0) { + return NULL; + } + return resp; +} + +// see examples/wget.cpp +typedef std::function download_progress_cb; +HV_INLINE size_t downloadFile(const char* url, const char* filepath, download_progress_cb progress_cb = NULL) { + // open file + std::string filepath_download(filepath); + filepath_download += ".download"; + HFile file; + int ret = file.open(filepath_download.c_str(), "wb"); + if (ret != 0) { + return 0; + } + // download + auto req = std::make_shared(); + req->method = HTTP_GET; + req->url = url; + req->timeout = 3600; // 1h + size_t content_length = 0; + size_t received_bytes = 0; + req->http_cb = [&file, &content_length, &received_bytes, &progress_cb] + (HttpMessage* resp, http_parser_state state, const char* data, size_t size) { + if (!resp->headers["Location"].empty()) return; + if (state == HP_HEADERS_COMPLETE) { + content_length = hv::from_string(resp->GetHeader("Content-Length")); + } else if (state == HP_BODY) { + if (data && size) { + // write file + file.write(data, size); + received_bytes += size; + if (progress_cb) { + progress_cb(received_bytes, content_length); + } + } + } + }; + auto resp = request(req); + file.close(); + if (resp == NULL || resp->status_code != 200) { + return 0; + } + // check filesize + if (content_length != 0 && hv_filesize(filepath_download.c_str()) != content_length) { + remove(filepath_download.c_str()); + return 0; + } + rename(filepath_download.c_str(), filepath); + return hv_filesize(filepath); +} + +} + +#endif // HV_REQUESTS_H_ diff --git a/external/libhv/libhv-1.3.2/http/grpcdef.h b/external/libhv/libhv-1.3.2/http/grpcdef.h new file mode 100644 index 0000000..7bbf29d --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/grpcdef.h @@ -0,0 +1,89 @@ +#ifndef HV_GRPC_DEF_H_ +#define HV_GRPC_DEF_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +// Length-Prefixed-Message + +// flags:1byte + length:4bytes = 5bytes +#define GRPC_MESSAGE_HDLEN 5 + +typedef struct { + unsigned char flags; + unsigned int length; +} grpc_message_hd; + +typedef struct { + unsigned char flags; + unsigned int length; + unsigned char* message; +} grpc_message; + +static inline void grpc_message_hd_pack(const grpc_message_hd* hd, unsigned char* buf) { + unsigned char* p = buf; + // flags + *p++ = hd->flags; + // hton length + unsigned int length = hd->length; + *p++ = (length >> 24) & 0xFF; + *p++ = (length >> 16) & 0xFF; + *p++ = (length >> 8) & 0xFF; + *p++ = length & 0xFF; +} + +static inline void grpc_message_hd_unpack(grpc_message_hd* hd, const unsigned char* buf) { + const unsigned char* p = buf; + // flags + hd->flags = *p++; + // ntoh length + hd->length = ((unsigned int)*p++) << 24; + hd->length |= ((unsigned int)*p++) << 16; + hd->length |= ((unsigned int)*p++) << 8; + hd->length |= *p++; +} + +// protobuf +// tag = field_num << 3 | wire_type +// varint(tag) [+ varint(length_delimited)] + value; +typedef enum { + WIRE_TYPE_VARINT = 0, + WIRE_TYPE_FIXED64 = 1, + WIRE_TYPE_LENGTH_DELIMITED = 2, + WIRE_TYPE_START_GROUP = 3, + WIRE_TYPE_END_GROUP = 4, + WIRE_TYPE_FIXED32 = 5, +} wire_type; + +typedef enum { + FIELD_TYPE_DOUBLE = 1, + FIELD_TYPE_FLOAT = 2, + FIELD_TYPE_INT64 = 3, + FIELD_TYPE_UINT64 = 4, + FIELD_TYPE_INT32 = 5, + FIELD_TYPE_FIXED64 = 6, + FIELD_TYPE_FIXED32 = 7, + FIELD_TYPE_BOOL = 8, + FIELD_TYPE_STRING = 9, + FIELD_TYPE_GROUP = 10, + FIELD_TYPE_MESSAGE = 11, + FIELD_TYPE_BYTES = 12, + FIELD_TYPE_UINT32 = 13, + FIELD_TYPE_ENUM = 14, + FIELD_TYPE_SFIXED32 = 15, + FIELD_TYPE_SFIXED64 = 16, + FIELD_TYPE_SINT32 = 17, + FIELD_TYPE_SINT64 = 18, + MAX_FIELD_TYPE = 18, +} field_type; + +#define PROTOBUF_MAKE_TAG(field_number, wire_type) ((field_number) << 3 | (wire_type)) +#define PROTOBUF_FILED_NUMBER(tag) ((tag) >> 3) +#define PROTOBUF_WIRE_TYPE(tag) ((tag) & 0x07) + +#ifdef __cplusplus +} +#endif + +#endif // HV_GRPC_DEF_H_ diff --git a/external/libhv/libhv-1.3.2/http/http2def.h b/external/libhv/libhv-1.3.2/http/http2def.h new file mode 100644 index 0000000..7a4d831 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/http2def.h @@ -0,0 +1,86 @@ +#ifndef HV_HTTP2_DEF_H_ +#define HV_HTTP2_DEF_H_ + +#ifdef __cplusplus +extern "C" { +#endif + + +#define HTTP2_MAGIC "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" +#define HTTP2_MAGIC_LEN 24 + +// length:3bytes + type:1byte + flags:1byte + stream_id:4bytes = 9bytes +#define HTTP2_FRAME_HDLEN 9 + +#define HTTP2_UPGRADE_RESPONSE \ +"HTTP/1.1 101 Switching Protocols\r\n"\ +"Connection: Upgrade\r\n"\ +"Upgrade: h2c\r\n\r\n" + +typedef enum { + HTTP2_DATA = 0, + HTTP2_HEADERS = 0x01, + HTTP2_PRIORITY = 0x02, + HTTP2_RST_STREAM = 0x03, + HTTP2_SETTINGS = 0x04, + HTTP2_PUSH_PROMISE = 0x05, + HTTP2_PING = 0x06, + HTTP2_GOAWAY = 0x07, + HTTP2_WINDOW_UPDATE = 0x08, + HTTP2_CONTINUATION = 0x09, + HTTP2_ALTSVC = 0x0a, + HTTP2_ORIGIN = 0x0c +} http2_frame_type; + +typedef enum { + HTTP2_FLAG_NONE = 0, + HTTP2_FLAG_END_STREAM = 0x01, + HTTP2_FLAG_END_HEADERS = 0x04, + HTTP2_FLAG_PADDED = 0x08, + HTTP2_FLAG_PRIORITY = 0x20 +} http2_flag; + +typedef struct { + int length; + http2_frame_type type; + http2_flag flags; + int stream_id; +} http2_frame_hd; + +static inline void http2_frame_hd_pack(const http2_frame_hd* hd, unsigned char* buf) { + // hton + int length = hd->length; + int stream_id = hd->stream_id; + unsigned char* p = buf; + *p++ = (length >> 16) & 0xFF; + *p++ = (length >> 8) & 0xFF; + *p++ = length & 0xFF; + *p++ = (unsigned char)hd->type; + *p++ = (unsigned char)hd->flags; + *p++ = (stream_id >> 24) & 0xFF; + *p++ = (stream_id >> 16) & 0xFF; + *p++ = (stream_id >> 8) & 0xFF; + *p++ = stream_id & 0xFF; +} + +static inline void http2_frame_hd_unpack(const unsigned char* buf, http2_frame_hd* hd) { + // ntoh + const unsigned char* p = buf; + hd->length = *p++ << 16; + hd->length += *p++ << 8; + hd->length += *p++; + + hd->type = (http2_frame_type)*p++; + hd->flags = (http2_flag)*p++; + + hd->stream_id = *p++ << 24; + hd->stream_id += *p++ << 16; + hd->stream_id += *p++ << 8; + hd->stream_id += *p++; +} + +#ifdef __cplusplus +} +#endif + +#endif // HV_HTTP2_DEF_H_ diff --git a/external/libhv/libhv-1.3.2/http/http_content.cpp b/external/libhv/libhv-1.3.2/http/http_content.cpp new file mode 100644 index 0000000..65a2888 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/http_content.cpp @@ -0,0 +1,252 @@ +#include "http_content.h" + +#include "hurl.h" + +#include + +BEGIN_NAMESPACE_HV + +std::string dump_query_params(const QueryParams& query_params) { + std::string query_string; + for (auto& pair : query_params) { + if (query_string.size() != 0) { + query_string += '&'; + } + query_string += HUrl::escape(pair.first); + query_string += '='; + query_string += HUrl::escape(pair.second); + } + return query_string; +} + +int parse_query_params(const char* query_string, QueryParams& query_params) { + const char* p = strchr(query_string, '?'); + p = p ? p+1 : query_string; + + enum { + s_key, + s_value, + } state = s_key; + + const char* key = p; + const char* value = NULL; + int key_len = 0; + int value_len = 0; + while (*p != '\0') { + if (*p == '&') { + if (key_len /* && value_len */) { + std::string strkey = std::string(key, key_len); + std::string strvalue = std::string(value, value_len); + query_params[HUrl::unescape(strkey)] = HUrl::unescape(strvalue); + key_len = value_len = 0; + } + state = s_key; + key = p+1; + } + else if (*p == '=') { + state = s_value; + value = p+1; + } + else { + state == s_key ? ++key_len : ++value_len; + } + ++p; + } + if (key_len /* && value_len */) { + std::string strkey = std::string(key, key_len); + std::string strvalue = std::string(value, value_len); + query_params[HUrl::unescape(strkey)] = HUrl::unescape(strvalue); + key_len = value_len = 0; + } + return query_params.size() == 0 ? -1 : 0; +} + +#ifndef WITHOUT_HTTP_CONTENT + +#include "hstring.h" // for split +#include "hfile.h" +#include "httpdef.h" // for http_content_type_str_by_suffix + +std::string dump_multipart(MultiPart& mp, const char* boundary) { + char c_str[256] = {0}; + std::string str; + for (auto& pair : mp) { + str += "--"; + str += boundary; + str += "\r\n"; + str += "Content-Disposition: form-data"; + snprintf(c_str, sizeof(c_str), "; name=\"%s\"", pair.first.c_str()); + str += c_str; + auto& form = pair.second; + if (form.filename.size() != 0) { + if (form.content.size() == 0) { + HFile file; + if (file.open(form.filename.c_str(), "rb") == 0) { + file.readall(form.content); + } + } + snprintf(c_str, sizeof(c_str), "; filename=\"%s\"", hv_basename(form.filename.c_str())); + str += c_str; + const char* suffix = strrchr(form.filename.c_str(), '.'); + if (suffix) { + const char* stype = http_content_type_str_by_suffix(++suffix); + if (stype && *stype != '\0') { + str += "\r\n"; + str += "Content-Type: "; + str += stype; + } + } + } + str += "\r\n\r\n"; + str += form.content; + str += "\r\n"; + } + str += "--"; + str += boundary; + str += "--\r\n"; + return str; +} + +#include "multipart_parser.h" +enum multipart_parser_state_e { + MP_START, + MP_PART_DATA_BEGIN, + MP_HEADER_FIELD, + MP_HEADER_VALUE, + MP_HEADERS_COMPLETE, + MP_PART_DATA, + MP_PART_DATA_END, + MP_BODY_END +}; +struct multipart_parser_userdata { + MultiPart* mp; + // tmp + multipart_parser_state_e state; + std::string header_field; + std::string header_value; + std::string part_data; + std::string name; + std::string filename; + + void handle_header() { + if (header_field.size() == 0 || header_value.size() == 0) return; + if (stricmp(header_field.c_str(), "Content-Disposition") == 0) { + StringList strlist = split(header_value, ';'); + for (auto& str : strlist) { + StringList kv = split(trim(str, " "), '='); + if (kv.size() == 2) { + const char* key = kv.begin()->c_str(); + std::string value = *(kv.begin() + 1); + value = trim_pairs(value, "\"\"\'\'"); + if (strcmp(key, "name") == 0) { + name = value; + } + else if (strcmp(key, "filename") == 0) { + filename = value; + } + } + } + } + header_field.clear(); + header_value.clear(); + } + + void handle_data() { + if (name.size() != 0) { + FormData formdata; + formdata.content = part_data; + formdata.filename = filename; + (*mp)[name] = formdata; + } + name.clear(); + filename.clear(); + part_data.clear(); + } +}; +static int on_header_field(multipart_parser* parser, const char *at, size_t length) { + //printf("on_header_field:%.*s\n", (int)length, at); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->handle_header(); + userdata->state = MP_HEADER_FIELD; + userdata->header_field.append(at, length); + return 0; +} +static int on_header_value(multipart_parser* parser, const char *at, size_t length) { + //printf("on_header_value:%.*s\n", (int)length, at); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->state = MP_HEADER_VALUE; + userdata->header_value.append(at, length); + return 0; +} +static int on_part_data(multipart_parser* parser, const char *at, size_t length) { + //printf("on_part_data:%.*s\n", (int)length, at); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->state = MP_PART_DATA; + userdata->part_data.append(at, length); + return 0; +} +static int on_part_data_begin(multipart_parser* parser) { + //printf("on_part_data_begin\n"); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->state = MP_PART_DATA_BEGIN; + return 0; +} +static int on_headers_complete(multipart_parser* parser) { + //printf("on_headers_complete\n"); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->handle_header(); + userdata->state = MP_HEADERS_COMPLETE; + return 0; +} +static int on_part_data_end(multipart_parser* parser) { + //printf("on_part_data_end\n"); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->state = MP_PART_DATA_END; + userdata->handle_data(); + return 0; +} +static int on_body_end(multipart_parser* parser) { + //printf("on_body_end\n"); + multipart_parser_userdata* userdata = (multipart_parser_userdata*)multipart_parser_get_data(parser); + userdata->state = MP_BODY_END; + return 0; +} +int parse_multipart(const std::string& str, MultiPart& mp, const char* boundary) { + //printf("boundary=%s\n", boundary); + std::string __boundary("--"); + __boundary += boundary; + multipart_parser_settings settings; + settings.on_header_field = on_header_field; + settings.on_header_value = on_header_value; + settings.on_part_data = on_part_data; + settings.on_part_data_begin = on_part_data_begin; + settings.on_headers_complete = on_headers_complete; + settings.on_part_data_end = on_part_data_end; + settings.on_body_end = on_body_end; + multipart_parser* parser = multipart_parser_init(__boundary.c_str(), &settings); + multipart_parser_userdata userdata; + userdata.state = MP_START; + userdata.mp = ∓ + multipart_parser_set_data(parser, &userdata); + size_t nparse = multipart_parser_execute(parser, str.c_str(), str.size()); + multipart_parser_free(parser); + return nparse == str.size() ? 0 : -1; +} + +std::string dump_json(const hv::Json& json, int indent) { + return json.dump(indent); +} + +int parse_json(const char* str, hv::Json& json, std::string& errmsg) { + try { + json = nlohmann::json::parse(str); + } + catch(nlohmann::detail::exception e) { + errmsg = e.what(); + return -1; + } + return (json.is_discarded() || json.is_null()) ? -1 : 0; +} +#endif + +END_NAMESPACE_HV diff --git a/external/libhv/libhv-1.3.2/http/http_content.h b/external/libhv/libhv-1.3.2/http/http_content.h new file mode 100644 index 0000000..11890ee --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/http_content.h @@ -0,0 +1,78 @@ +#ifndef HV_HTTP_CONTENT_H_ +#define HV_HTTP_CONTENT_H_ + +#include "hexport.h" +#include "hstring.h" + +// NOTE: WITHOUT_HTTP_CONTENT +// ndk-r10e no std::to_string and can't compile modern json.hpp +#ifndef WITHOUT_HTTP_CONTENT +#include "json.hpp" // https://github.com/nlohmann/json +#endif + +BEGIN_NAMESPACE_HV + +// QueryParams +using QueryParams = hv::KeyValue; +HV_EXPORT std::string dump_query_params(const QueryParams& query_params); +HV_EXPORT int parse_query_params(const char* query_string, QueryParams& query_params); + +#ifndef WITHOUT_HTTP_CONTENT + +/**************multipart/form-data************************************* +--boundary +Content-Disposition: form-data; name="user" + +content +--boundary +Content-Disposition: form-data; name="avatar"; filename="user.jpg" +Content-Type: image/jpeg + +content +--boundary-- +***********************************************************************/ +// FormData +struct FormData { + std::string filename; + std::string content; + + FormData(const char* content = NULL, const char* filename = NULL) { + if (content) { + this->content = content; + } + if (filename) { + this->filename = filename; + } + } + template + FormData(T num) { + content = hv::to_string(num); + } +}; +// FormFile +struct FormFile : public FormData { + FormFile(const char* filename = NULL) { + if (filename) { + this->filename = filename; + } + } +}; + +// MultiPart +// name => FormData +typedef HV_MAP MultiPart; +#define DEFAULT_MULTIPART_BOUNDARY "----WebKitFormBoundary7MA4YWxkTrZu0gW" +HV_EXPORT std::string dump_multipart(MultiPart& mp, const char* boundary = DEFAULT_MULTIPART_BOUNDARY); +HV_EXPORT int parse_multipart(const std::string& str, MultiPart& mp, const char* boundary); + +// Json +using Json = nlohmann::json; +// using Json = nlohmann::ordered_json; + +HV_EXPORT std::string dump_json(const hv::Json& json, int indent = -1); +HV_EXPORT int parse_json(const char* str, hv::Json& json, std::string& errmsg); +#endif + +END_NAMESPACE_HV + +#endif // HV_HTTP_CONTENT_H_ diff --git a/external/libhv/libhv-1.3.2/http/http_parser.c b/external/libhv/libhv-1.3.2/http/http_parser.c new file mode 100644 index 0000000..659cfb2 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/http_parser.c @@ -0,0 +1,2481 @@ +/* Copyright Joyent, Inc. and other Node contributors. + * + * 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. + */ +#include "http_parser.h" +#include +#include +#include +#include +#include + +static uint32_t max_header_size = HTTP_MAX_HEADER_SIZE; + +#ifndef ULLONG_MAX +# define ULLONG_MAX ((uint64_t) -1) /* 2^64-1 */ +#endif + +#ifndef MIN +# define MIN(a,b) ((a) < (b) ? (a) : (b)) +#endif + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#endif + +#ifndef BIT_AT +# define BIT_AT(a, i) \ + (!!((unsigned int) (a)[(unsigned int) (i) >> 3] & \ + (1 << ((unsigned int) (i) & 7)))) +#endif + +#ifndef ELEM_AT +# define ELEM_AT(a, i, v) ((unsigned int) (i) < ARRAY_SIZE(a) ? (a)[(i)] : (v)) +#endif + +#define SET_ERRNO(e) \ +do { \ + parser->nread = nread; \ + parser->http_errno = (e); \ +} while(0) + +#define CURRENT_STATE() p_state +#define UPDATE_STATE(V) p_state = (enum state) (V); +#define RETURN(V) \ +do { \ + parser->nread = nread; \ + parser->state = CURRENT_STATE(); \ + return (V); \ +} while (0); +#define REEXECUTE() \ + goto reexecute; \ + + +#ifdef __GNUC__ +# define LIKELY(X) __builtin_expect(!!(X), 1) +# define UNLIKELY(X) __builtin_expect(!!(X), 0) +#else +# define LIKELY(X) (X) +# define UNLIKELY(X) (X) +#endif + + +/* Run the notify callback FOR, returning ER if it fails */ +#define CALLBACK_NOTIFY_(FOR, ER) \ +do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (LIKELY(settings->on_##FOR)) { \ + parser->state = CURRENT_STATE(); \ + if (UNLIKELY(0 != settings->on_##FOR(parser))) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + UPDATE_STATE(parser->state); \ + \ + /* We either errored above or got paused; get out */ \ + if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ + return (ER); \ + } \ + } \ +} while (0) + +/* Run the notify callback FOR and consume the current byte */ +#define CALLBACK_NOTIFY(FOR) CALLBACK_NOTIFY_(FOR, p - data + 1) + +/* Run the notify callback FOR and don't consume the current byte */ +#define CALLBACK_NOTIFY_NOADVANCE(FOR) CALLBACK_NOTIFY_(FOR, p - data) + +/* Run data callback FOR with LEN bytes, returning ER if it fails */ +#define CALLBACK_DATA_(FOR, LEN, ER) \ +do { \ + assert(HTTP_PARSER_ERRNO(parser) == HPE_OK); \ + \ + if (FOR##_mark) { \ + if (LIKELY(settings->on_##FOR)) { \ + parser->state = CURRENT_STATE(); \ + if (UNLIKELY(0 != \ + settings->on_##FOR(parser, FOR##_mark, (LEN)))) { \ + SET_ERRNO(HPE_CB_##FOR); \ + } \ + UPDATE_STATE(parser->state); \ + \ + /* We either errored above or got paused; get out */ \ + if (UNLIKELY(HTTP_PARSER_ERRNO(parser) != HPE_OK)) { \ + return (ER); \ + } \ + } \ + FOR##_mark = NULL; \ + } \ +} while (0) + +/* Run the data callback FOR and consume the current byte */ +#define CALLBACK_DATA(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data + 1) + +/* Run the data callback FOR and don't consume the current byte */ +#define CALLBACK_DATA_NOADVANCE(FOR) \ + CALLBACK_DATA_(FOR, p - FOR##_mark, p - data) + +/* Set the mark FOR; non-destructive if mark is already set */ +#define MARK(FOR) \ +do { \ + if (!FOR##_mark) { \ + FOR##_mark = p; \ + } \ +} while (0) + +/* Don't allow the total size of the HTTP headers (including the status + * line) to exceed max_header_size. This check is here to protect + * embedders against denial-of-service attacks where the attacker feeds + * us a never-ending header that the embedder keeps buffering. + * + * This check is arguably the responsibility of embedders but we're doing + * it on the embedder's behalf because most won't bother and this way we + * make the web a little safer. max_header_size is still far bigger + * than any reasonable request or response so this should never affect + * day-to-day operation. + */ +#define COUNT_HEADER_SIZE(V) \ +do { \ + nread += (uint32_t)(V); \ + if (UNLIKELY(nread > max_header_size)) { \ + SET_ERRNO(HPE_HEADER_OVERFLOW); \ + goto error; \ + } \ +} while (0) + + +#define PROXY_CONNECTION "proxy-connection" +#define CONNECTION "connection" +#define CONTENT_LENGTH "content-length" +#define TRANSFER_ENCODING "transfer-encoding" +#define UPGRADE "upgrade" +#define CHUNKED "chunked" +#define KEEP_ALIVE "keep-alive" +#define CLOSE "close" + + +static const char *method_strings[] = + { +#define XX(num, name, string) #string, + HTTP_METHOD_MAP(XX) +#undef XX + }; + + +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +static const char tokens[256] = { +/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0, 0, 0, 0, 0, 0, 0, 0, +/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + ' ', '!', 0, '#', '$', '%', '&', '\'', +/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 0, 0, '*', '+', 0, '-', '.', 0, +/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + '0', '1', '2', '3', '4', '5', '6', '7', +/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + '8', '9', 0, 0, 0, 0, 0, 0, +/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', +/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', +/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', +/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 'x', 'y', 'z', 0, 0, 0, '^', '_', +/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', +/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', +/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', +/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 'x', 'y', 'z', 0, '|', 0, '~', 0 }; + + +static const int8_t unhex[256] = + {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + , 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1 + ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1 + ,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 + }; + + +#if HTTP_PARSER_STRICT +# define T(v) 0 +#else +# define T(v) v +#endif + + +static const uint8_t normal_url_char[32] = { +/* 0 nul 1 soh 2 stx 3 etx 4 eot 5 enq 6 ack 7 bel */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, +/* 8 bs 9 ht 10 nl 11 vt 12 np 13 cr 14 so 15 si */ + 0 | T(2) | 0 | 0 | T(16) | 0 | 0 | 0, +/* 16 dle 17 dc1 18 dc2 19 dc3 20 dc4 21 nak 22 syn 23 etb */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, +/* 24 can 25 em 26 sub 27 esc 28 fs 29 gs 30 rs 31 us */ + 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0, +/* 32 sp 33 ! 34 " 35 # 36 $ 37 % 38 & 39 ' */ + 0 | 2 | 4 | 0 | 16 | 32 | 64 | 128, +/* 40 ( 41 ) 42 * 43 + 44 , 45 - 46 . 47 / */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 48 0 49 1 50 2 51 3 52 4 53 5 54 6 55 7 */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 56 8 57 9 58 : 59 ; 60 < 61 = 62 > 63 ? */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, +/* 64 @ 65 A 66 B 67 C 68 D 69 E 70 F 71 G */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 72 H 73 I 74 J 75 K 76 L 77 M 78 N 79 O */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 80 P 81 Q 82 R 83 S 84 T 85 U 86 V 87 W */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 88 X 89 Y 90 Z 91 [ 92 \ 93 ] 94 ^ 95 _ */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 96 ` 97 a 98 b 99 c 100 d 101 e 102 f 103 g */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 104 h 105 i 106 j 107 k 108 l 109 m 110 n 111 o */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 112 p 113 q 114 r 115 s 116 t 117 u 118 v 119 w */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128, +/* 120 x 121 y 122 z 123 { 124 | 125 } 126 ~ 127 del */ + 1 | 2 | 4 | 8 | 16 | 32 | 64 | 0, }; + +#undef T + +enum state + { s_dead = 1 /* important that this is > 0 */ + + , s_start_req_or_res + , s_res_or_resp_H + , s_start_res + , s_res_H + , s_res_HT + , s_res_HTT + , s_res_HTTP + , s_res_http_major + , s_res_http_dot + , s_res_http_minor + , s_res_http_end + , s_res_first_status_code + , s_res_status_code + , s_res_status_start + , s_res_status + , s_res_line_almost_done + + , s_start_req + + , s_req_method + , s_req_spaces_before_url + , s_req_schema + , s_req_schema_slash + , s_req_schema_slash_slash + , s_req_server_start + , s_req_server + , s_req_server_with_at + , s_req_path + , s_req_query_string_start + , s_req_query_string + , s_req_fragment_start + , s_req_fragment + , s_req_http_start + , s_req_http_H + , s_req_http_HT + , s_req_http_HTT + , s_req_http_HTTP + , s_req_http_I + , s_req_http_IC + , s_req_http_major + , s_req_http_dot + , s_req_http_minor + , s_req_http_end + , s_req_line_almost_done + + , s_header_field_start + , s_header_field + , s_header_value_discard_ws + , s_header_value_discard_ws_almost_done + , s_header_value_discard_lws + , s_header_value_start + , s_header_value + , s_header_value_lws + + , s_header_almost_done + + , s_chunk_size_start + , s_chunk_size + , s_chunk_parameters + , s_chunk_size_almost_done + + , s_headers_almost_done + , s_headers_done + + /* Important: 's_headers_done' must be the last 'header' state. All + * states beyond this must be 'body' states. It is used for overflow + * checking. See the PARSING_HEADER() macro. + */ + + , s_chunk_data + , s_chunk_data_almost_done + , s_chunk_data_done + + , s_body_identity + , s_body_identity_eof + + , s_message_done + }; + + +#define PARSING_HEADER(state) (state <= s_headers_done) + + +enum header_states + { h_general = 0 + , h_C + , h_CO + , h_CON + + , h_matching_connection + , h_matching_proxy_connection + , h_matching_content_length + , h_matching_transfer_encoding + , h_matching_upgrade + + , h_connection + , h_content_length + , h_content_length_num + , h_content_length_ws + , h_transfer_encoding + , h_upgrade + + , h_matching_transfer_encoding_chunked + , h_matching_connection_token_start + , h_matching_connection_keep_alive + , h_matching_connection_close + , h_matching_connection_upgrade + , h_matching_connection_token + + , h_transfer_encoding_chunked + , h_connection_keep_alive + , h_connection_close + , h_connection_upgrade + }; + +enum http_host_state + { + s_http_host_dead = 1 + , s_http_userinfo_start + , s_http_userinfo + , s_http_host_start + , s_http_host_v6_start + , s_http_host + , s_http_host_v6 + , s_http_host_v6_end + , s_http_host_v6_zone_start + , s_http_host_v6_zone + , s_http_host_port_start + , s_http_host_port +}; + +/* Macros for character classes; depends on strict-mode */ +#define CR '\r' +#define LF '\n' +#define LOWER(c) (unsigned char)(c | 0x20) +#define IS_ALPHA(c) (LOWER(c) >= 'a' && LOWER(c) <= 'z') +#define IS_NUM(c) ((c) >= '0' && (c) <= '9') +#define IS_ALPHANUM(c) (IS_ALPHA(c) || IS_NUM(c)) +#define IS_HEX(c) (IS_NUM(c) || (LOWER(c) >= 'a' && LOWER(c) <= 'f')) +#define IS_MARK(c) ((c) == '-' || (c) == '_' || (c) == '.' || \ + (c) == '!' || (c) == '~' || (c) == '*' || (c) == '\'' || (c) == '(' || \ + (c) == ')') +#define IS_USERINFO_CHAR(c) (IS_ALPHANUM(c) || IS_MARK(c) || (c) == '%' || \ + (c) == ';' || (c) == ':' || (c) == '&' || (c) == '=' || (c) == '+' || \ + (c) == '$' || (c) == ',') + +#define STRICT_TOKEN(c) ((c == ' ') ? 0 : tokens[(unsigned char)c]) + +#if HTTP_PARSER_STRICT +#define TOKEN(c) STRICT_TOKEN(c) +#define IS_URL_CHAR(c) (BIT_AT(normal_url_char, (unsigned char)c)) +#define IS_HOST_CHAR(c) (IS_ALPHANUM(c) || (c) == '.' || (c) == '-') +#else +#define TOKEN(c) tokens[(unsigned char)c] +#define IS_URL_CHAR(c) \ + (BIT_AT(normal_url_char, (unsigned char)c) || ((c) & 0x80)) +#define IS_HOST_CHAR(c) \ + (IS_ALPHANUM(c) || (c) == '.' || (c) == '-' || (c) == '_') +#endif + +/** + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + **/ +#define IS_HEADER_CHAR(ch) \ + (ch == CR || ch == LF || ch == 9 || ((unsigned char)ch > 31 && ch != 127)) + +#define start_state (parser->type == HTTP_REQUEST ? s_start_req : s_start_res) + + +#if HTTP_PARSER_STRICT +# define STRICT_CHECK(cond) \ +do { \ + if (cond) { \ + SET_ERRNO(HPE_STRICT); \ + goto error; \ + } \ +} while (0) +# define NEW_MESSAGE() (http_should_keep_alive(parser) ? start_state : s_dead) +#else +# define STRICT_CHECK(cond) +# define NEW_MESSAGE() start_state +#endif + + +/* Map errno values to strings for human-readable output */ +#define HTTP_STRERROR_GEN(n, s) { "HPE_" #n, s }, +static struct { + const char *name; + const char *description; +} http_strerror_tab[] = { + HTTP_ERRNO_MAP(HTTP_STRERROR_GEN) +}; +#undef HTTP_STRERROR_GEN + +int http_message_needs_eof(const http_parser *parser); + +/* Our URL parser. + * + * This is designed to be shared by http_parser_execute() for URL validation, + * hence it has a state transition + byte-for-byte interface. In addition, it + * is meant to be embedded in http_parser_parse_url(), which does the dirty + * work of turning state transitions URL components for its API. + * + * This function should only be invoked with non-space characters. It is + * assumed that the caller cares about (and can detect) the transition between + * URL and non-URL states by looking for these. + */ +static enum state +parse_url_char(enum state s, const char ch) +{ + if (ch == ' ' || ch == '\r' || ch == '\n') { + return s_dead; + } + +#if HTTP_PARSER_STRICT + if (ch == '\t' || ch == '\f') { + return s_dead; + } +#endif + + switch (s) { + case s_req_spaces_before_url: + /* Proxied requests are followed by scheme of an absolute URI (alpha). + * All methods except CONNECT are followed by '/' or '*'. + */ + + if (ch == '/' || ch == '*') { + return s_req_path; + } + + if (IS_ALPHA(ch)) { + return s_req_schema; + } + + break; + + case s_req_schema: + if (IS_ALPHA(ch)) { + return s; + } + + if (ch == ':') { + return s_req_schema_slash; + } + + break; + + case s_req_schema_slash: + if (ch == '/') { + return s_req_schema_slash_slash; + } + + break; + + case s_req_schema_slash_slash: + if (ch == '/') { + return s_req_server_start; + } + + break; + + case s_req_server_with_at: + if (ch == '@') { + return s_dead; + } + + /* fall through */ + case s_req_server_start: + case s_req_server: + if (ch == '/') { + return s_req_path; + } + + if (ch == '?') { + return s_req_query_string_start; + } + + if (ch == '@') { + return s_req_server_with_at; + } + + if (IS_USERINFO_CHAR(ch) || ch == '[' || ch == ']') { + return s_req_server; + } + + break; + + case s_req_path: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + return s_req_query_string_start; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_query_string_start: + case s_req_query_string: + if (IS_URL_CHAR(ch)) { + return s_req_query_string; + } + + switch (ch) { + case '?': + /* allow extra '?' in query string */ + return s_req_query_string; + + case '#': + return s_req_fragment_start; + } + + break; + + case s_req_fragment_start: + if (IS_URL_CHAR(ch)) { + return s_req_fragment; + } + + switch (ch) { + case '?': + return s_req_fragment; + + case '#': + return s; + } + + break; + + case s_req_fragment: + if (IS_URL_CHAR(ch)) { + return s; + } + + switch (ch) { + case '?': + case '#': + return s; + } + + break; + + default: + break; + } + + /* We should never fall out of the switch above unless there's an error */ + return s_dead; +} + +size_t http_parser_execute (http_parser *parser, + const http_parser_settings *settings, + const char *data, + size_t len) +{ + char c, ch; + int8_t unhex_val; + const char *p = data; + const char *header_field_mark = 0; + const char *header_value_mark = 0; + const char *url_mark = 0; + const char *body_mark = 0; + const char *status_mark = 0; + enum state p_state = (enum state) parser->state; + const unsigned int lenient = parser->lenient_http_headers; + uint32_t nread = parser->nread; + + /* We're in an error state. Don't bother doing anything. */ + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + return 0; + } + + if (len == 0) { + switch (CURRENT_STATE()) { + case s_body_identity_eof: + /* Use of CALLBACK_NOTIFY() here would erroneously return 1 byte read if + * we got paused. + */ + CALLBACK_NOTIFY_NOADVANCE(message_complete); + return 0; + + case s_dead: + case s_start_req_or_res: + case s_start_res: + case s_start_req: + return 0; + + default: + SET_ERRNO(HPE_INVALID_EOF_STATE); + return 1; + } + } + + + if (CURRENT_STATE() == s_header_field) + header_field_mark = data; + if (CURRENT_STATE() == s_header_value) + header_value_mark = data; + switch (CURRENT_STATE()) { + case s_req_path: + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: + case s_req_server: + case s_req_server_with_at: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: + url_mark = data; + break; + case s_res_status: + status_mark = data; + break; + default: + break; + } + + for (p=data; p != data + len; p++) { + ch = *p; + + if (PARSING_HEADER(CURRENT_STATE())) + COUNT_HEADER_SIZE(1); + +reexecute: + switch (CURRENT_STATE()) { + + case s_dead: + /* this state is used after a 'Connection: close' message + * the parser will error out if it reads another message + */ + if (LIKELY(ch == CR || ch == LF)) + break; + + SET_ERRNO(HPE_CLOSED_CONNECTION); + goto error; + + case s_start_req_or_res: + { + if (ch == CR || ch == LF) + break; + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (ch == 'H') { + UPDATE_STATE(s_res_or_resp_H); + + CALLBACK_NOTIFY(message_begin); + } else { + parser->type = HTTP_REQUEST; + UPDATE_STATE(s_start_req); + REEXECUTE(); + } + + break; + } + + case s_res_or_resp_H: + if (ch == 'T') { + parser->type = HTTP_RESPONSE; + UPDATE_STATE(s_res_HT); + } else { + if (UNLIKELY(ch != 'E')) { + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + parser->type = HTTP_REQUEST; + parser->method = HTTP_HEAD; + parser->index = 2; + UPDATE_STATE(s_req_method); + } + break; + + case s_start_res: + { + if (ch == CR || ch == LF) + break; + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (ch == 'H') { + UPDATE_STATE(s_res_H); + } else { + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + + CALLBACK_NOTIFY(message_begin); + break; + } + + case s_res_H: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_res_HT); + break; + + case s_res_HT: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_res_HTT); + break; + + case s_res_HTT: + STRICT_CHECK(ch != 'P'); + UPDATE_STATE(s_res_HTTP); + break; + + case s_res_HTTP: + STRICT_CHECK(ch != '/'); + UPDATE_STATE(s_res_http_major); + break; + + case s_res_http_major: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + UPDATE_STATE(s_res_http_dot); + break; + + case s_res_http_dot: + { + if (UNLIKELY(ch != '.')) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + UPDATE_STATE(s_res_http_minor); + break; + } + + case s_res_http_minor: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + UPDATE_STATE(s_res_http_end); + break; + + case s_res_http_end: + { + if (UNLIKELY(ch != ' ')) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + UPDATE_STATE(s_res_first_status_code); + break; + } + + case s_res_first_status_code: + { + if (!IS_NUM(ch)) { + if (ch == ' ') { + break; + } + + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + parser->status_code = ch - '0'; + UPDATE_STATE(s_res_status_code); + break; + } + + case s_res_status_code: + { + if (!IS_NUM(ch)) { + switch (ch) { + case ' ': + UPDATE_STATE(s_res_status_start); + break; + case CR: + case LF: + UPDATE_STATE(s_res_status_start); + REEXECUTE(); + break; + default: + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + break; + } + + parser->status_code *= 10; + parser->status_code += ch - '0'; + + if (UNLIKELY(parser->status_code > 999)) { + SET_ERRNO(HPE_INVALID_STATUS); + goto error; + } + + break; + } + + case s_res_status_start: + { + MARK(status); + UPDATE_STATE(s_res_status); + parser->index = 0; + + if (ch == CR || ch == LF) + REEXECUTE(); + + break; + } + + case s_res_status: + if (ch == CR) { + UPDATE_STATE(s_res_line_almost_done); + CALLBACK_DATA(status); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_field_start); + CALLBACK_DATA(status); + break; + } + + break; + + case s_res_line_almost_done: + STRICT_CHECK(ch != LF); + UPDATE_STATE(s_header_field_start); + break; + + case s_start_req: + { + if (ch == CR || ch == LF) + break; + parser->flags = 0; + parser->content_length = ULLONG_MAX; + + if (UNLIKELY(!IS_ALPHA(ch))) { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + parser->method = (enum http_method) 0; + parser->index = 1; + switch (ch) { + case 'A': parser->method = HTTP_ACL; break; + case 'B': parser->method = HTTP_BIND; break; + case 'C': parser->method = HTTP_CONNECT; /* or COPY, CHECKOUT */ break; + case 'D': parser->method = HTTP_DELETE; break; + case 'G': parser->method = HTTP_GET; break; + case 'H': parser->method = HTTP_HEAD; break; + case 'L': parser->method = HTTP_LOCK; /* or LINK */ break; + case 'M': parser->method = HTTP_MKCOL; /* or MOVE, MKACTIVITY, MERGE, M-SEARCH, MKCALENDAR */ break; + case 'N': parser->method = HTTP_NOTIFY; break; + case 'O': parser->method = HTTP_OPTIONS; break; + case 'P': parser->method = HTTP_POST; + /* or PROPFIND|PROPPATCH|PUT|PATCH|PURGE */ + break; + case 'R': parser->method = HTTP_REPORT; /* or REBIND */ break; + case 'S': parser->method = HTTP_SUBSCRIBE; /* or SEARCH, SOURCE */ break; + case 'T': parser->method = HTTP_TRACE; break; + case 'U': parser->method = HTTP_UNLOCK; /* or UNSUBSCRIBE, UNBIND, UNLINK */ break; + default: + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + UPDATE_STATE(s_req_method); + + CALLBACK_NOTIFY(message_begin); + + break; + } + + case s_req_method: + { + const char *matcher; + if (UNLIKELY(ch == '\0')) { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + matcher = method_strings[parser->method]; + if (ch == ' ' && matcher[parser->index] == '\0') { + UPDATE_STATE(s_req_spaces_before_url); + } else if (ch == matcher[parser->index]) { + ; /* nada */ + } else if ((ch >= 'A' && ch <= 'Z') || ch == '-') { + + switch (parser->method << 16 | parser->index << 8 | ch) { +#define XX(meth, pos, ch, new_meth) \ + case (HTTP_##meth << 16 | pos << 8 | ch): \ + parser->method = HTTP_##new_meth; break; + + XX(POST, 1, 'U', PUT) + XX(POST, 1, 'A', PATCH) + XX(POST, 1, 'R', PROPFIND) + XX(PUT, 2, 'R', PURGE) + XX(CONNECT, 1, 'H', CHECKOUT) + XX(CONNECT, 2, 'P', COPY) + XX(MKCOL, 1, 'O', MOVE) + XX(MKCOL, 1, 'E', MERGE) + XX(MKCOL, 1, '-', MSEARCH) + XX(MKCOL, 2, 'A', MKACTIVITY) + XX(MKCOL, 3, 'A', MKCALENDAR) + XX(SUBSCRIBE, 1, 'E', SEARCH) + XX(SUBSCRIBE, 1, 'O', SOURCE) + XX(REPORT, 2, 'B', REBIND) + XX(PROPFIND, 4, 'P', PROPPATCH) + XX(LOCK, 1, 'I', LINK) + XX(UNLOCK, 2, 'S', UNSUBSCRIBE) + XX(UNLOCK, 2, 'B', UNBIND) + XX(UNLOCK, 3, 'I', UNLINK) +#undef XX + default: + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + } else { + SET_ERRNO(HPE_INVALID_METHOD); + goto error; + } + + ++parser->index; + break; + } + + case s_req_spaces_before_url: + { + if (ch == ' ') break; + + MARK(url); + if (parser->method == HTTP_CONNECT) { + UPDATE_STATE(s_req_server_start); + } + + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + + break; + } + + case s_req_schema: + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: + { + switch (ch) { + /* No whitespace allowed here */ + case ' ': + case CR: + case LF: + SET_ERRNO(HPE_INVALID_URL); + goto error; + default: + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + + break; + } + + case s_req_server: + case s_req_server_with_at: + case s_req_path: + case s_req_query_string_start: + case s_req_query_string: + case s_req_fragment_start: + case s_req_fragment: + { + switch (ch) { + case ' ': + UPDATE_STATE(s_req_http_start); + CALLBACK_DATA(url); + break; + case CR: + case LF: + parser->http_major = 0; + parser->http_minor = 9; + UPDATE_STATE((ch == CR) ? + s_req_line_almost_done : + s_header_field_start); + CALLBACK_DATA(url); + break; + default: + UPDATE_STATE(parse_url_char(CURRENT_STATE(), ch)); + if (UNLIKELY(CURRENT_STATE() == s_dead)) { + SET_ERRNO(HPE_INVALID_URL); + goto error; + } + } + break; + } + + case s_req_http_start: + switch (ch) { + case ' ': + break; + case 'H': + UPDATE_STATE(s_req_http_H); + break; + case 'I': + if (parser->method == HTTP_SOURCE) { + UPDATE_STATE(s_req_http_I); + break; + } + /* fall through */ + default: + SET_ERRNO(HPE_INVALID_CONSTANT); + goto error; + } + break; + + case s_req_http_H: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_req_http_HT); + break; + + case s_req_http_HT: + STRICT_CHECK(ch != 'T'); + UPDATE_STATE(s_req_http_HTT); + break; + + case s_req_http_HTT: + STRICT_CHECK(ch != 'P'); + UPDATE_STATE(s_req_http_HTTP); + break; + + case s_req_http_I: + STRICT_CHECK(ch != 'C'); + UPDATE_STATE(s_req_http_IC); + break; + + case s_req_http_IC: + STRICT_CHECK(ch != 'E'); + UPDATE_STATE(s_req_http_HTTP); /* Treat "ICE" as "HTTP". */ + break; + + case s_req_http_HTTP: + STRICT_CHECK(ch != '/'); + UPDATE_STATE(s_req_http_major); + break; + + case s_req_http_major: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_major = ch - '0'; + UPDATE_STATE(s_req_http_dot); + break; + + case s_req_http_dot: + { + if (UNLIKELY(ch != '.')) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + UPDATE_STATE(s_req_http_minor); + break; + } + + case s_req_http_minor: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + } + + parser->http_minor = ch - '0'; + UPDATE_STATE(s_req_http_end); + break; + + case s_req_http_end: + { + if (ch == CR) { + UPDATE_STATE(s_req_line_almost_done); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_field_start); + break; + } + + SET_ERRNO(HPE_INVALID_VERSION); + goto error; + break; + } + + /* end of request line */ + case s_req_line_almost_done: + { + if (UNLIKELY(ch != LF)) { + SET_ERRNO(HPE_LF_EXPECTED); + goto error; + } + + UPDATE_STATE(s_header_field_start); + break; + } + + case s_header_field_start: + { + if (ch == CR) { + UPDATE_STATE(s_headers_almost_done); + break; + } + + if (ch == LF) { + /* they might be just sending \n instead of \r\n so this would be + * the second \n to denote the end of headers*/ + UPDATE_STATE(s_headers_almost_done); + REEXECUTE(); + } + + c = TOKEN(ch); + + if (UNLIKELY(!c)) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + MARK(header_field); + + parser->index = 0; + UPDATE_STATE(s_header_field); + + switch (c) { + case 'c': + parser->header_state = h_C; + break; + + case 'p': + parser->header_state = h_matching_proxy_connection; + break; + + case 't': + parser->header_state = h_matching_transfer_encoding; + break; + + case 'u': + parser->header_state = h_matching_upgrade; + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_field: + { + const char* start = p; + for (; p != data + len; p++) { + ch = *p; + c = TOKEN(ch); + + if (!c) + break; + + switch (parser->header_state) { + case h_general: { + size_t limit = data + len - p; + limit = MIN(limit, max_header_size); + while (p+1 < data + limit && TOKEN(p[1])) { + p++; + } + break; + } + + case h_C: + parser->index++; + parser->header_state = (c == 'o' ? h_CO : h_general); + break; + + case h_CO: + parser->index++; + parser->header_state = (c == 'n' ? h_CON : h_general); + break; + + case h_CON: + parser->index++; + switch (c) { + case 'n': + parser->header_state = h_matching_connection; + break; + case 't': + parser->header_state = h_matching_content_length; + break; + default: + parser->header_state = h_general; + break; + } + break; + + /* connection */ + + case h_matching_connection: + parser->index++; + if (parser->index > sizeof(CONNECTION)-1 + || c != CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONNECTION)-2) { + parser->header_state = h_connection; + } + break; + + /* proxy-connection */ + + case h_matching_proxy_connection: + parser->index++; + if (parser->index > sizeof(PROXY_CONNECTION)-1 + || c != PROXY_CONNECTION[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(PROXY_CONNECTION)-2) { + parser->header_state = h_connection; + } + break; + + /* content-length */ + + case h_matching_content_length: + parser->index++; + if (parser->index > sizeof(CONTENT_LENGTH)-1 + || c != CONTENT_LENGTH[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(CONTENT_LENGTH)-2) { + parser->header_state = h_content_length; + } + break; + + /* transfer-encoding */ + + case h_matching_transfer_encoding: + parser->index++; + if (parser->index > sizeof(TRANSFER_ENCODING)-1 + || c != TRANSFER_ENCODING[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(TRANSFER_ENCODING)-2) { + parser->header_state = h_transfer_encoding; + } + break; + + /* upgrade */ + + case h_matching_upgrade: + parser->index++; + if (parser->index > sizeof(UPGRADE)-1 + || c != UPGRADE[parser->index]) { + parser->header_state = h_general; + } else if (parser->index == sizeof(UPGRADE)-2) { + parser->header_state = h_upgrade; + } + break; + + case h_connection: + case h_content_length: + case h_transfer_encoding: + case h_upgrade: + if (ch != ' ') parser->header_state = h_general; + break; + + default: + assert(0 && "Unknown header_state"); + break; + } + } + + if (p == data + len) { + --p; + COUNT_HEADER_SIZE(p - start); + break; + } + + COUNT_HEADER_SIZE(p - start); + + if (ch == ':') { + UPDATE_STATE(s_header_value_discard_ws); + CALLBACK_DATA(header_field); + break; + } + + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + case s_header_value_discard_ws: + if (ch == ' ' || ch == '\t') break; + + if (ch == CR) { + UPDATE_STATE(s_header_value_discard_ws_almost_done); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_value_discard_lws); + break; + } + + /* fall through */ + + case s_header_value_start: + { + MARK(header_value); + + UPDATE_STATE(s_header_value); + parser->index = 0; + + c = LOWER(ch); + + switch (parser->header_state) { + case h_upgrade: + parser->flags |= F_UPGRADE; + parser->header_state = h_general; + break; + + case h_transfer_encoding: + /* looking for 'Transfer-Encoding: chunked' */ + if ('c' == c) { + parser->header_state = h_matching_transfer_encoding_chunked; + } else { + parser->header_state = h_general; + } + break; + + case h_content_length: + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + if (parser->flags & F_CONTENTLENGTH) { + SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); + goto error; + } + + parser->flags |= F_CONTENTLENGTH; + parser->content_length = ch - '0'; + parser->header_state = h_content_length_num; + break; + + /* when obsolete line folding is encountered for content length + * continue to the s_header_value state */ + case h_content_length_ws: + break; + + case h_connection: + /* looking for 'Connection: keep-alive' */ + if (c == 'k') { + parser->header_state = h_matching_connection_keep_alive; + /* looking for 'Connection: close' */ + } else if (c == 'c') { + parser->header_state = h_matching_connection_close; + } else if (c == 'u') { + parser->header_state = h_matching_connection_upgrade; + } else { + parser->header_state = h_matching_connection_token; + } + break; + + /* Multi-value `Connection` header */ + case h_matching_connection_token_start: + break; + + default: + parser->header_state = h_general; + break; + } + break; + } + + case s_header_value: + { + const char* start = p; + enum header_states h_state = (enum header_states) parser->header_state; + for (; p != data + len; p++) { + ch = *p; + if (ch == CR) { + UPDATE_STATE(s_header_almost_done); + parser->header_state = h_state; + CALLBACK_DATA(header_value); + break; + } + + if (ch == LF) { + UPDATE_STATE(s_header_almost_done); + COUNT_HEADER_SIZE(p - start); + parser->header_state = h_state; + CALLBACK_DATA_NOADVANCE(header_value); + REEXECUTE(); + } + + if (!lenient && !IS_HEADER_CHAR(ch)) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + + c = LOWER(ch); + + switch (h_state) { + case h_general: + { + const char* limit = p + MIN(data + len - p, max_header_size); + + for (; p != limit; p++) { + ch = *p; + if (ch == CR || ch == LF) { + --p; + break; + } + if (!lenient && !IS_HEADER_CHAR(ch)) { + SET_ERRNO(HPE_INVALID_HEADER_TOKEN); + goto error; + } + } + if (p == data + len) + --p; + break; + } + + case h_connection: + case h_transfer_encoding: + assert(0 && "Shouldn't get here."); + break; + + case h_content_length: + if (ch == ' ') break; + h_state = h_content_length_num; + /* fall through */ + + case h_content_length_num: + { + uint64_t t; + + if (ch == ' ') { + h_state = h_content_length_ws; + break; + } + + if (UNLIKELY(!IS_NUM(ch))) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = h_state; + goto error; + } + + t = parser->content_length; + t *= 10; + t += ch - '0'; + + /* Overflow? Test against a conservative limit for simplicity. */ + if (UNLIKELY((ULLONG_MAX - 10) / 10 < parser->content_length)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = h_state; + goto error; + } + + parser->content_length = t; + break; + } + + case h_content_length_ws: + if (ch == ' ') break; + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + parser->header_state = h_state; + goto error; + + /* Transfer-Encoding: chunked */ + case h_matching_transfer_encoding_chunked: + parser->index++; + if (parser->index > sizeof(CHUNKED)-1 + || c != CHUNKED[parser->index]) { + h_state = h_general; + } else if (parser->index == sizeof(CHUNKED)-2) { + h_state = h_transfer_encoding_chunked; + } + break; + + case h_matching_connection_token_start: + /* looking for 'Connection: keep-alive' */ + if (c == 'k') { + h_state = h_matching_connection_keep_alive; + /* looking for 'Connection: close' */ + } else if (c == 'c') { + h_state = h_matching_connection_close; + } else if (c == 'u') { + h_state = h_matching_connection_upgrade; + } else if (STRICT_TOKEN(c)) { + h_state = h_matching_connection_token; + } else if (c == ' ' || c == '\t') { + /* Skip lws */ + } else { + h_state = h_general; + } + break; + + /* looking for 'Connection: keep-alive' */ + case h_matching_connection_keep_alive: + parser->index++; + if (parser->index > sizeof(KEEP_ALIVE)-1 + || c != KEEP_ALIVE[parser->index]) { + h_state = h_matching_connection_token; + } else if (parser->index == sizeof(KEEP_ALIVE)-2) { + h_state = h_connection_keep_alive; + } + break; + + /* looking for 'Connection: close' */ + case h_matching_connection_close: + parser->index++; + if (parser->index > sizeof(CLOSE)-1 || c != CLOSE[parser->index]) { + h_state = h_matching_connection_token; + } else if (parser->index == sizeof(CLOSE)-2) { + h_state = h_connection_close; + } + break; + + /* looking for 'Connection: upgrade' */ + case h_matching_connection_upgrade: + parser->index++; + if (parser->index > sizeof(UPGRADE) - 1 || + c != UPGRADE[parser->index]) { + h_state = h_matching_connection_token; + } else if (parser->index == sizeof(UPGRADE)-2) { + h_state = h_connection_upgrade; + } + break; + + case h_matching_connection_token: + if (ch == ',') { + h_state = h_matching_connection_token_start; + parser->index = 0; + } + break; + + case h_transfer_encoding_chunked: + if (ch != ' ') h_state = h_general; + break; + + case h_connection_keep_alive: + case h_connection_close: + case h_connection_upgrade: + if (ch == ',') { + if (h_state == h_connection_keep_alive) { + parser->flags |= F_CONNECTION_KEEP_ALIVE; + } else if (h_state == h_connection_close) { + parser->flags |= F_CONNECTION_CLOSE; + } else if (h_state == h_connection_upgrade) { + parser->flags |= F_CONNECTION_UPGRADE; + } + h_state = h_matching_connection_token_start; + parser->index = 0; + } else if (ch != ' ') { + h_state = h_matching_connection_token; + } + break; + + default: + UPDATE_STATE(s_header_value); + h_state = h_general; + break; + } + } + parser->header_state = h_state; + + if (p == data + len) + --p; + + COUNT_HEADER_SIZE(p - start); + break; + } + + case s_header_almost_done: + { + if (UNLIKELY(ch != LF)) { + SET_ERRNO(HPE_LF_EXPECTED); + goto error; + } + + UPDATE_STATE(s_header_value_lws); + break; + } + + case s_header_value_lws: + { + if (ch == ' ' || ch == '\t') { + if (parser->header_state == h_content_length_num) { + /* treat obsolete line folding as space */ + parser->header_state = h_content_length_ws; + } + UPDATE_STATE(s_header_value_start); + REEXECUTE(); + } + + /* finished the header */ + switch (parser->header_state) { + case h_connection_keep_alive: + parser->flags |= F_CONNECTION_KEEP_ALIVE; + break; + case h_connection_close: + parser->flags |= F_CONNECTION_CLOSE; + break; + case h_transfer_encoding_chunked: + parser->flags |= F_CHUNKED; + break; + case h_connection_upgrade: + parser->flags |= F_CONNECTION_UPGRADE; + break; + default: + break; + } + + UPDATE_STATE(s_header_field_start); + REEXECUTE(); + } + + case s_header_value_discard_ws_almost_done: + { + STRICT_CHECK(ch != LF); + UPDATE_STATE(s_header_value_discard_lws); + break; + } + + case s_header_value_discard_lws: + { + if (ch == ' ' || ch == '\t') { + UPDATE_STATE(s_header_value_discard_ws); + break; + } else { + switch (parser->header_state) { + case h_connection_keep_alive: + parser->flags |= F_CONNECTION_KEEP_ALIVE; + break; + case h_connection_close: + parser->flags |= F_CONNECTION_CLOSE; + break; + case h_connection_upgrade: + parser->flags |= F_CONNECTION_UPGRADE; + break; + case h_transfer_encoding_chunked: + parser->flags |= F_CHUNKED; + break; + case h_content_length: + /* do not allow empty content length */ + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + break; + default: + break; + } + + /* header value was empty */ + MARK(header_value); + UPDATE_STATE(s_header_field_start); + CALLBACK_DATA_NOADVANCE(header_value); + REEXECUTE(); + } + } + + case s_headers_almost_done: + { + STRICT_CHECK(ch != LF); + + if (parser->flags & F_TRAILING) { + /* End of a chunked request */ + UPDATE_STATE(s_message_done); + CALLBACK_NOTIFY_NOADVANCE(chunk_complete); + REEXECUTE(); + } + + /* Cannot use chunked encoding and a content-length header together + per the HTTP specification. */ + if ((parser->flags & F_CHUNKED) && + (parser->flags & F_CONTENTLENGTH)) { + SET_ERRNO(HPE_UNEXPECTED_CONTENT_LENGTH); + goto error; + } + + UPDATE_STATE(s_headers_done); + + /* Set this here so that on_headers_complete() callbacks can see it */ + if ((parser->flags & F_UPGRADE) && + (parser->flags & F_CONNECTION_UPGRADE)) { + /* For responses, "Upgrade: foo" and "Connection: upgrade" are + * mandatory only when it is a 101 Switching Protocols response, + * otherwise it is purely informational, to announce support. + */ + parser->upgrade = + (parser->type == HTTP_REQUEST || parser->status_code == 101); + } else { + parser->upgrade = (parser->method == HTTP_CONNECT); + } + + /* Here we call the headers_complete callback. This is somewhat + * different than other callbacks because if the user returns 1, we + * will interpret that as saying that this message has no body. This + * is needed for the annoying case of recieving a response to a HEAD + * request. + * + * We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so + * we have to simulate it by handling a change in errno below. + */ + if (settings->on_headers_complete) { + switch (settings->on_headers_complete(parser)) { + case 0: + break; + + case 2: + parser->upgrade = 1; + + /* fall through */ + case 1: + parser->flags |= F_SKIPBODY; + break; + + default: + SET_ERRNO(HPE_CB_headers_complete); + RETURN(p - data); /* Error */ + } + } + + if (HTTP_PARSER_ERRNO(parser) != HPE_OK) { + RETURN(p - data); + } + + REEXECUTE(); + } + + case s_headers_done: + { + int hasBody; + STRICT_CHECK(ch != LF); + + parser->nread = 0; + nread = 0; + + hasBody = parser->flags & F_CHUNKED || + (parser->content_length > 0 && parser->content_length != ULLONG_MAX); + if (parser->upgrade && (parser->method == HTTP_CONNECT || + (parser->flags & F_SKIPBODY) || !hasBody)) { + /* Exit, the rest of the message is in a different protocol. */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + RETURN((p - data) + 1); + } + + if (parser->flags & F_SKIPBODY) { + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else if (parser->flags & F_CHUNKED) { + /* chunked encoding - ignore Content-Length header */ + UPDATE_STATE(s_chunk_size_start); + } else { + if (parser->content_length == 0) { + /* Content-Length header given but zero: Content-Length: 0\r\n */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else if (parser->content_length != ULLONG_MAX) { + /* Content-Length header given and non-zero */ + UPDATE_STATE(s_body_identity); + } else { + if (!http_message_needs_eof(parser)) { + /* Assume content-length 0 - read the next */ + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + } else { + /* Read body until EOF */ + UPDATE_STATE(s_body_identity_eof); + } + } + } + + break; + } + + case s_body_identity: + { + uint64_t to_read = MIN(parser->content_length, + (uint64_t) ((data + len) - p)); + + assert(parser->content_length != 0 + && parser->content_length != ULLONG_MAX); + + /* The difference between advancing content_length and p is because + * the latter will automaticaly advance on the next loop iteration. + * Further, if content_length ends up at 0, we want to see the last + * byte again for our message complete callback. + */ + MARK(body); + parser->content_length -= to_read; + p += to_read - 1; + + if (parser->content_length == 0) { + UPDATE_STATE(s_message_done); + + /* Mimic CALLBACK_DATA_NOADVANCE() but with one extra byte. + * + * The alternative to doing this is to wait for the next byte to + * trigger the data callback, just as in every other case. The + * problem with this is that this makes it difficult for the test + * harness to distinguish between complete-on-EOF and + * complete-on-length. It's not clear that this distinction is + * important for applications, but let's keep it for now. + */ + CALLBACK_DATA_(body, p - body_mark + 1, p - data); + REEXECUTE(); + } + + break; + } + + /* read until EOF */ + case s_body_identity_eof: + MARK(body); + p = data + len - 1; + + break; + + case s_message_done: + UPDATE_STATE(NEW_MESSAGE()); + CALLBACK_NOTIFY(message_complete); + if (parser->upgrade) { + /* Exit, the rest of the message is in a different protocol. */ + RETURN((p - data) + 1); + } + break; + + case s_chunk_size_start: + { + assert(nread == 1); + assert(parser->flags & F_CHUNKED); + + unhex_val = unhex[(unsigned char)ch]; + if (UNLIKELY(unhex_val == -1)) { + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + parser->content_length = unhex_val; + UPDATE_STATE(s_chunk_size); + break; + } + + case s_chunk_size: + { + uint64_t t; + + assert(parser->flags & F_CHUNKED); + + if (ch == CR) { + UPDATE_STATE(s_chunk_size_almost_done); + break; + } + + unhex_val = unhex[(unsigned char)ch]; + + if (unhex_val == -1) { + if (ch == ';' || ch == ' ') { + UPDATE_STATE(s_chunk_parameters); + break; + } + + SET_ERRNO(HPE_INVALID_CHUNK_SIZE); + goto error; + } + + t = parser->content_length; + t *= 16; + t += unhex_val; + + /* Overflow? Test against a conservative limit for simplicity. */ + if (UNLIKELY((ULLONG_MAX - 16) / 16 < parser->content_length)) { + SET_ERRNO(HPE_INVALID_CONTENT_LENGTH); + goto error; + } + + parser->content_length = t; + break; + } + + case s_chunk_parameters: + { + assert(parser->flags & F_CHUNKED); + /* just ignore this shit. TODO check for overflow */ + if (ch == CR) { + UPDATE_STATE(s_chunk_size_almost_done); + break; + } + break; + } + + case s_chunk_size_almost_done: + { + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + + parser->nread = 0; + nread = 0; + + if (parser->content_length == 0) { + parser->flags |= F_TRAILING; + UPDATE_STATE(s_header_field_start); + } else { + UPDATE_STATE(s_chunk_data); + } + CALLBACK_NOTIFY(chunk_header); + break; + } + + case s_chunk_data: + { + uint64_t to_read = MIN(parser->content_length, + (uint64_t) ((data + len) - p)); + + assert(parser->flags & F_CHUNKED); + assert(parser->content_length != 0 + && parser->content_length != ULLONG_MAX); + + /* See the explanation in s_body_identity for why the content + * length and data pointers are managed this way. + */ + MARK(body); + parser->content_length -= to_read; + p += to_read - 1; + + if (parser->content_length == 0) { + UPDATE_STATE(s_chunk_data_almost_done); + } + + break; + } + + case s_chunk_data_almost_done: + assert(parser->flags & F_CHUNKED); + assert(parser->content_length == 0); + STRICT_CHECK(ch != CR); + UPDATE_STATE(s_chunk_data_done); + CALLBACK_DATA(body); + break; + + case s_chunk_data_done: + assert(parser->flags & F_CHUNKED); + STRICT_CHECK(ch != LF); + parser->nread = 0; + nread = 0; + UPDATE_STATE(s_chunk_size_start); + CALLBACK_NOTIFY(chunk_complete); + break; + + default: + assert(0 && "unhandled state"); + SET_ERRNO(HPE_INVALID_INTERNAL_STATE); + goto error; + } + } + + /* Run callbacks for any marks that we have leftover after we ran out of + * bytes. There should be at most one of these set, so it's OK to invoke + * them in series (unset marks will not result in callbacks). + * + * We use the NOADVANCE() variety of callbacks here because 'p' has already + * overflowed 'data' and this allows us to correct for the off-by-one that + * we'd otherwise have (since CALLBACK_DATA() is meant to be run with a 'p' + * value that's in-bounds). + */ + + assert(((header_field_mark ? 1 : 0) + + (header_value_mark ? 1 : 0) + + (url_mark ? 1 : 0) + + (body_mark ? 1 : 0) + + (status_mark ? 1 : 0)) <= 1); + + CALLBACK_DATA_NOADVANCE(header_field); + CALLBACK_DATA_NOADVANCE(header_value); + CALLBACK_DATA_NOADVANCE(url); + CALLBACK_DATA_NOADVANCE(body); + CALLBACK_DATA_NOADVANCE(status); + + RETURN(len); + +error: + if (HTTP_PARSER_ERRNO(parser) == HPE_OK) { + SET_ERRNO(HPE_UNKNOWN); + } + + RETURN(p - data); +} + + +/* Does the parser need to see an EOF to find the end of the message? */ +int +http_message_needs_eof (const http_parser *parser) +{ + if (parser->type == HTTP_REQUEST) { + return 0; + } + + /* See RFC 2616 section 4.4 */ + if (parser->status_code / 100 == 1 || /* 1xx e.g. Continue */ + parser->status_code == 204 || /* No Content */ + parser->status_code == 304 || /* Not Modified */ + parser->flags & F_SKIPBODY) { /* response to a HEAD request */ + return 0; + } + + if ((parser->flags & F_CHUNKED) || parser->content_length != ULLONG_MAX) { + return 0; + } + + return 1; +} + + +int +http_should_keep_alive (const http_parser *parser) +{ + if (parser->http_major > 0 && parser->http_minor > 0) { + /* HTTP/1.1 */ + if (parser->flags & F_CONNECTION_CLOSE) { + return 0; + } + } else { + /* HTTP/1.0 or earlier */ + if (!(parser->flags & F_CONNECTION_KEEP_ALIVE)) { + return 0; + } + } + + return !http_message_needs_eof(parser); +} + +void +http_parser_init (http_parser *parser, enum http_parser_type t) +{ + void *data = parser->data; /* preserve application data */ + memset(parser, 0, sizeof(*parser)); + parser->data = data; + parser->type = t; + parser->state = (t == HTTP_REQUEST ? s_start_req : (t == HTTP_RESPONSE ? s_start_res : s_start_req_or_res)); + parser->http_errno = HPE_OK; +} + +void +http_parser_settings_init(http_parser_settings *settings) +{ + memset(settings, 0, sizeof(*settings)); +} + +const char * +http_errno_name(enum http_errno err) { + assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); + return http_strerror_tab[err].name; +} + +const char * +http_errno_description(enum http_errno err) { + assert(((size_t) err) < ARRAY_SIZE(http_strerror_tab)); + return http_strerror_tab[err].description; +} + +#ifdef WITH_HTTP_PRASER_URL +static enum http_host_state +http_parse_host_char(enum http_host_state s, const char ch) { + switch(s) { + case s_http_userinfo: + case s_http_userinfo_start: + if (ch == '@') { + return s_http_host_start; + } + + if (IS_USERINFO_CHAR(ch)) { + return s_http_userinfo; + } + break; + + case s_http_host_start: + if (ch == '[') { + return s_http_host_v6_start; + } + + if (IS_HOST_CHAR(ch)) { + return s_http_host; + } + + break; + + case s_http_host: + if (IS_HOST_CHAR(ch)) { + return s_http_host; + } + + /* fall through */ + case s_http_host_v6_end: + if (ch == ':') { + return s_http_host_port_start; + } + + break; + + case s_http_host_v6: + if (ch == ']') { + return s_http_host_v6_end; + } + + /* fall through */ + case s_http_host_v6_start: + if (IS_HEX(ch) || ch == ':' || ch == '.') { + return s_http_host_v6; + } + + if (s == s_http_host_v6 && ch == '%') { + return s_http_host_v6_zone_start; + } + break; + + case s_http_host_v6_zone: + if (ch == ']') { + return s_http_host_v6_end; + } + + /* fall through */ + case s_http_host_v6_zone_start: + /* RFC 6874 Zone ID consists of 1*( unreserved / pct-encoded) */ + if (IS_ALPHANUM(ch) || ch == '%' || ch == '.' || ch == '-' || ch == '_' || + ch == '~') { + return s_http_host_v6_zone; + } + break; + + case s_http_host_port: + case s_http_host_port_start: + if (IS_NUM(ch)) { + return s_http_host_port; + } + + break; + + default: + break; + } + return s_http_host_dead; +} + +static int +http_parse_host(const char * buf, struct http_parser_url *u, int found_at) { + enum http_host_state s; + + const char *p; + size_t buflen = u->field_data[UF_HOST].off + u->field_data[UF_HOST].len; + + assert(u->field_set & (1 << UF_HOST)); + + u->field_data[UF_HOST].len = 0; + + s = found_at ? s_http_userinfo_start : s_http_host_start; + + for (p = buf + u->field_data[UF_HOST].off; p < buf + buflen; p++) { + enum http_host_state new_s = http_parse_host_char(s, *p); + + if (new_s == s_http_host_dead) { + return 1; + } + + switch(new_s) { + case s_http_host: + if (s != s_http_host) { + u->field_data[UF_HOST].off = (uint16_t)(p - buf); + } + u->field_data[UF_HOST].len++; + break; + + case s_http_host_v6: + if (s != s_http_host_v6) { + u->field_data[UF_HOST].off = (uint16_t)(p - buf); + } + u->field_data[UF_HOST].len++; + break; + + case s_http_host_v6_zone_start: + case s_http_host_v6_zone: + u->field_data[UF_HOST].len++; + break; + + case s_http_host_port: + if (s != s_http_host_port) { + u->field_data[UF_PORT].off = (uint16_t)(p - buf); + u->field_data[UF_PORT].len = 0; + u->field_set |= (1 << UF_PORT); + } + u->field_data[UF_PORT].len++; + break; + + case s_http_userinfo: + if (s != s_http_userinfo) { + u->field_data[UF_USERINFO].off = (uint16_t)(p - buf); + u->field_data[UF_USERINFO].len = 0; + u->field_set |= (1 << UF_USERINFO); + } + u->field_data[UF_USERINFO].len++; + break; + + default: + break; + } + s = new_s; + } + + /* Make sure we don't end somewhere unexpected */ + switch (s) { + case s_http_host_start: + case s_http_host_v6_start: + case s_http_host_v6: + case s_http_host_v6_zone_start: + case s_http_host_v6_zone: + case s_http_host_port_start: + case s_http_userinfo: + case s_http_userinfo_start: + return 1; + default: + break; + } + + return 0; +} + +void +http_parser_url_init(struct http_parser_url *u) { + memset(u, 0, sizeof(*u)); +} + +int +http_parser_parse_url(const char *buf, size_t buflen, int is_connect, + struct http_parser_url *u) +{ + enum state s; + const char *p; + enum http_parser_url_fields uf, old_uf; + int found_at = 0; + + if (buflen == 0) { + return 1; + } + + u->port = u->field_set = 0; + s = is_connect ? s_req_server_start : s_req_spaces_before_url; + old_uf = UF_MAX; + + for (p = buf; p < buf + buflen; p++) { + s = parse_url_char(s, *p); + + /* Figure out the next field that we're operating on */ + switch (s) { + case s_dead: + return 1; + + /* Skip delimeters */ + case s_req_schema_slash: + case s_req_schema_slash_slash: + case s_req_server_start: + case s_req_query_string_start: + case s_req_fragment_start: + continue; + + case s_req_schema: + uf = UF_SCHEMA; + break; + + case s_req_server_with_at: + found_at = 1; + + /* fall through */ + case s_req_server: + uf = UF_HOST; + break; + + case s_req_path: + uf = UF_PATH; + break; + + case s_req_query_string: + uf = UF_QUERY; + break; + + case s_req_fragment: + uf = UF_FRAGMENT; + break; + + default: + assert(!"Unexpected state"); + return 1; + } + + /* Nothing's changed; soldier on */ + if (uf == old_uf) { + u->field_data[uf].len++; + continue; + } + + u->field_data[uf].off = (uint16_t)(p - buf); + u->field_data[uf].len = 1; + + u->field_set |= (1 << uf); + old_uf = uf; + } + + /* host must be present if there is a schema */ + /* parsing http:///toto will fail */ + if ((u->field_set & (1 << UF_SCHEMA)) && + (u->field_set & (1 << UF_HOST)) == 0) { + return 1; + } + + if (u->field_set & (1 << UF_HOST)) { + if (http_parse_host(buf, u, found_at) != 0) { + return 1; + } + } + + /* CONNECT requests can only contain "hostname:port" */ + if (is_connect && u->field_set != ((1 << UF_HOST)|(1 << UF_PORT))) { + return 1; + } + + if (u->field_set & (1 << UF_PORT)) { + uint16_t off; + uint16_t len; + const char* p; + const char* end; + unsigned long v; + + off = u->field_data[UF_PORT].off; + len = u->field_data[UF_PORT].len; + end = buf + off + len; + + /* NOTE: The characters are already validated and are in the [0-9] range */ + assert(off + len <= buflen && "Port number overflow"); + v = 0; + for (p = buf + off; p < end; p++) { + v *= 10; + v += *p - '0'; + + /* Ports have a max value of 2^16 */ + if (v > 0xffff) { + return 1; + } + } + + u->port = (uint16_t) v; + } + + return 0; +} +#endif + +void +http_parser_pause(http_parser *parser, int paused) { + /* Users should only be pausing/unpausing a parser that is not in an error + * state. In non-debug builds, there's not much that we can do about this + * other than ignore it. + */ + if (HTTP_PARSER_ERRNO(parser) == HPE_OK || + HTTP_PARSER_ERRNO(parser) == HPE_PAUSED) { + uint32_t nread = parser->nread; /* used by the SET_ERRNO macro */ + SET_ERRNO((paused) ? HPE_PAUSED : HPE_OK); + } else { + assert(0 && "Attempting to pause parser in error state"); + } +} + +int +http_body_is_final(const struct http_parser *parser) { + return parser->state == s_message_done; +} + +unsigned long +http_parser_version(void) { + return HTTP_PARSER_VERSION_MAJOR * 0x10000 | + HTTP_PARSER_VERSION_MINOR * 0x00100 | + HTTP_PARSER_VERSION_PATCH * 0x00001; +} + +void +http_parser_set_max_header_size(uint32_t size) { + max_header_size = size; +} diff --git a/external/libhv/libhv-1.3.2/http/http_parser.h b/external/libhv/libhv-1.3.2/http/http_parser.h new file mode 100644 index 0000000..99ee789 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/http_parser.h @@ -0,0 +1,311 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * 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. + */ +#ifndef http_parser_h +#define http_parser_h +#ifdef __cplusplus +extern "C" { +#endif +#include "httpdef.h" + +/* Also update SONAME in the Makefile whenever you change these. */ +#define HTTP_PARSER_VERSION_MAJOR 2 +#define HTTP_PARSER_VERSION_MINOR 9 +#define HTTP_PARSER_VERSION_PATCH 1 + +#include +#if defined(_WIN32) && !defined(__MINGW32__) && \ + (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__) +#include +typedef __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include +#endif + +/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run + * faster + */ +#ifndef HTTP_PARSER_STRICT +# define HTTP_PARSER_STRICT 1 +#endif + +/* Maximium header size allowed. If the macro is not defined + * before including this header then the default is used. To + * change the maximum header size, define the macro in the build + * environment (e.g. -DHTTP_MAX_HEADER_SIZE=). To remove + * the effective limit on the size of the header, define the macro + * to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff) + */ +#ifndef HTTP_MAX_HEADER_SIZE +# define HTTP_MAX_HEADER_SIZE (80*1024) +#endif + +typedef struct http_parser http_parser; +typedef struct http_parser_settings http_parser_settings; + +/* Callbacks should return non-zero to indicate an error. The parser will + * then halt execution. + * + * The one exception is on_headers_complete. In a HTTP_RESPONSE parser + * returning '1' from on_headers_complete will tell the parser that it + * should not expect a body. This is used when receiving a response to a + * HEAD request which may contain 'Content-Length' or 'Transfer-Encoding: + * chunked' headers that indicate the presence of a body. + * + * Returning `2` from on_headers_complete will tell parser that it should not + * expect neither a body nor any futher responses on this connection. This is + * useful for handling responses to a CONNECT request which may not contain + * `Upgrade` or `Connection: upgrade` headers. + * + * http_data_cb does not return data chunks. It will be called arbitrarily + * many times for each string. E.G. you might get 10 callbacks for "on_url" + * each providing just a few characters more data. + */ +typedef int (*http_data_cb) (http_parser*, const char *at, size_t length); +typedef int (*http_cb) (http_parser*); + + +/* Flag values for http_parser.flags field */ +enum flags + { F_CHUNKED = 1 << 0 + , F_CONNECTION_KEEP_ALIVE = 1 << 1 + , F_CONNECTION_CLOSE = 1 << 2 + , F_CONNECTION_UPGRADE = 1 << 3 + , F_TRAILING = 1 << 4 + , F_UPGRADE = 1 << 5 + , F_SKIPBODY = 1 << 6 + , F_CONTENTLENGTH = 1 << 7 + }; + + +/* Map for errno-related constants + * + * The provided argument should be a macro that takes 2 arguments. + */ +#define HTTP_ERRNO_MAP(XX) \ + /* No error */ \ + XX(OK, "success") \ + \ + /* Callback-related errors */ \ + XX(CB_message_begin, "the on_message_begin callback failed") \ + XX(CB_url, "the on_url callback failed") \ + XX(CB_header_field, "the on_header_field callback failed") \ + XX(CB_header_value, "the on_header_value callback failed") \ + XX(CB_headers_complete, "the on_headers_complete callback failed") \ + XX(CB_body, "the on_body callback failed") \ + XX(CB_message_complete, "the on_message_complete callback failed") \ + XX(CB_status, "the on_status callback failed") \ + XX(CB_chunk_header, "the on_chunk_header callback failed") \ + XX(CB_chunk_complete, "the on_chunk_complete callback failed") \ + \ + /* Parsing-related errors */ \ + XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \ + XX(HEADER_OVERFLOW, \ + "too many header bytes seen; overflow detected") \ + XX(CLOSED_CONNECTION, \ + "data received after completed connection: close message") \ + XX(INVALID_VERSION, "invalid HTTP version") \ + XX(INVALID_STATUS, "invalid HTTP status code") \ + XX(INVALID_METHOD, "invalid HTTP method") \ + XX(INVALID_URL, "invalid URL") \ + XX(INVALID_HOST, "invalid host") \ + XX(INVALID_PORT, "invalid port") \ + XX(INVALID_PATH, "invalid path") \ + XX(INVALID_QUERY_STRING, "invalid query string") \ + XX(INVALID_FRAGMENT, "invalid fragment") \ + XX(LF_EXPECTED, "LF character expected") \ + XX(INVALID_HEADER_TOKEN, "invalid character in header") \ + XX(INVALID_CONTENT_LENGTH, \ + "invalid character in content-length header") \ + XX(UNEXPECTED_CONTENT_LENGTH, \ + "unexpected content-length header") \ + XX(INVALID_CHUNK_SIZE, \ + "invalid character in chunk size header") \ + XX(INVALID_CONSTANT, "invalid constant string") \ + XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\ + XX(STRICT, "strict mode assertion failed") \ + XX(PAUSED, "parser is paused") \ + XX(UNKNOWN, "an unknown error occurred") + + +/* Define HPE_* values for each errno value above */ +#define HTTP_ERRNO_GEN(n, s) HPE_##n, +enum http_errno { + HTTP_ERRNO_MAP(HTTP_ERRNO_GEN) +}; +#undef HTTP_ERRNO_GEN + + +/* Get an http_errno value from an http_parser */ +#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno) + + +struct http_parser { + /** PRIVATE **/ + unsigned int type : 2; /* enum http_parser_type */ + unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */ + unsigned int state : 7; /* enum state from http_parser.c */ + unsigned int header_state : 7; /* enum header_state from http_parser.c */ + unsigned int index : 7; /* index into current matcher */ + unsigned int lenient_http_headers : 1; + + uint32_t nread; /* # bytes read in various scenarios */ + uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */ + + /** READ-ONLY **/ + unsigned short http_major; + unsigned short http_minor; + unsigned int status_code : 16; /* responses only */ + unsigned int method : 8; /* requests only */ + unsigned int http_errno : 7; + + /* 1 = Upgrade header was present and the parser has exited because of that. + * 0 = No upgrade header present. + * Should be checked when http_parser_execute() returns in addition to + * error checking. + */ + unsigned int upgrade : 1; + + /** PUBLIC **/ + void *data; /* A pointer to get hook to the "connection" or "socket" object */ +}; + + +struct http_parser_settings { + http_cb on_message_begin; + http_data_cb on_url; + http_data_cb on_status; + http_data_cb on_header_field; + http_data_cb on_header_value; + http_cb on_headers_complete; + http_data_cb on_body; + http_cb on_message_complete; + /* When on_chunk_header is called, the current chunk length is stored + * in parser->content_length. + */ + http_cb on_chunk_header; + http_cb on_chunk_complete; +}; + + +#ifdef WITH_HTTP_PRASER_URL +enum http_parser_url_fields + { UF_SCHEMA = 0 + , UF_HOST = 1 + , UF_PORT = 2 + , UF_PATH = 3 + , UF_QUERY = 4 + , UF_FRAGMENT = 5 + , UF_USERINFO = 6 + , UF_MAX = 7 + }; + + +/* Result structure for http_parser_parse_url(). + * + * Callers should index into field_data[] with UF_* values iff field_set + * has the relevant (1 << UF_*) bit set. As a courtesy to clients (and + * because we probably have padding left over), we convert any port to + * a uint16_t. + */ +struct http_parser_url { + uint16_t field_set; /* Bitmask of (1 << UF_*) values */ + uint16_t port; /* Converted UF_PORT string */ + + struct { + uint16_t off; /* Offset into buffer in which field starts */ + uint16_t len; /* Length of run in buffer */ + } field_data[UF_MAX]; +}; +#endif + + +/* Returns the library version. Bits 16-23 contain the major version number, + * bits 8-15 the minor version number and bits 0-7 the patch level. + * Usage example: + * + * unsigned long version = http_parser_version(); + * unsigned major = (version >> 16) & 255; + * unsigned minor = (version >> 8) & 255; + * unsigned patch = version & 255; + * printf("http_parser v%u.%u.%u\n", major, minor, patch); + */ +unsigned long http_parser_version(void); + +void http_parser_init(http_parser *parser, enum http_parser_type type); + + +/* Initialize http_parser_settings members to 0 + */ +void http_parser_settings_init(http_parser_settings *settings); + + +/* Executes the parser. Returns number of parsed bytes. Sets + * `parser->http_errno` on error. */ +size_t http_parser_execute(http_parser *parser, + const http_parser_settings *settings, + const char *data, + size_t len); + + +/* If http_should_keep_alive() in the on_headers_complete or + * on_message_complete callback returns 0, then this should be + * the last message on the connection. + * If you are the server, respond with the "Connection: close" header. + * If you are the client, close the connection. + */ +int http_should_keep_alive(const http_parser *parser); + +/* Return a string name of the given error */ +const char *http_errno_name(enum http_errno err); + +/* Return a string description of the given error */ +const char *http_errno_description(enum http_errno err); + +#ifdef WITH_HTTP_PRASER_URL +/* Initialize all http_parser_url members to 0 */ +void http_parser_url_init(struct http_parser_url *u); + +/* Parse a URL; return nonzero on failure */ +int http_parser_parse_url(const char *buf, size_t buflen, + int is_connect, + struct http_parser_url *u); +#endif + +/* Pause or un-pause the parser; a nonzero value pauses */ +void http_parser_pause(http_parser *parser, int paused); + +/* Checks if this is the final chunk of the body. */ +int http_body_is_final(const http_parser *parser); + +/* Change the maximum header size provided at compile time. */ +void http_parser_set_max_header_size(uint32_t size); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/external/libhv/libhv-1.3.2/http/httpdef.c b/external/libhv/libhv-1.3.2/http/httpdef.c new file mode 100644 index 0000000..c791667 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/httpdef.c @@ -0,0 +1,106 @@ +#include "httpdef.h" + +#include + +static int strstartswith(const char* str, const char* start) { + while (*str && *start && *str == *start) { + ++str; + ++start; + } + return *start == '\0'; +} + +const char* http_status_str(enum http_status status) { + switch (status) { +#define XX(num, name, string) case HTTP_STATUS_##name: return #string; + HTTP_STATUS_MAP(XX) +#undef XX + default: return ""; + } +} + +const char* http_method_str(enum http_method method) { + switch (method) { +#define XX(num, name, string) case HTTP_##name: return #string; + HTTP_METHOD_MAP(XX) +#undef XX + default: return ""; + } +} + +const char* http_content_type_str(enum http_content_type type) { + switch (type) { +#define XX(name, string, suffix) case name: return #string; + HTTP_CONTENT_TYPE_MAP(XX) +#undef XX + default: return ""; + } +} + +enum http_status http_status_enum(const char* str) { +#define XX(num, name, string) \ + if (strcmp(str, #string) == 0) { \ + return HTTP_STATUS_##name; \ + } + HTTP_STATUS_MAP(XX) +#undef XX + return HTTP_CUSTOM_STATUS; +} + +enum http_method http_method_enum(const char* str) { +#define XX(num, name, string) \ + if (strcmp(str, #string) == 0) { \ + return HTTP_##name; \ + } + HTTP_METHOD_MAP(XX) +#undef XX + return HTTP_CUSTOM_METHOD; +} + +enum http_content_type http_content_type_enum(const char* str) { + if (!str || !*str) { + return CONTENT_TYPE_NONE; + } +#define XX(name, string, suffix) \ + if (strstartswith(str, #string)) { \ + return name; \ + } + HTTP_CONTENT_TYPE_MAP(XX) +#undef XX + return CONTENT_TYPE_UNDEFINED; +} + +const char* http_content_type_suffix(enum http_content_type type) { + switch (type) { +#define XX(name, string, suffix) case name: return #suffix; + HTTP_CONTENT_TYPE_MAP(XX) +#undef XX + default: return ""; + } +} + +const char* http_content_type_str_by_suffix(const char* str) { + if (!str || !*str) { + return ""; + } +#define XX(name, string, suffix) \ + if (strcmp(str, #suffix) == 0) { \ + return #string; \ + } + HTTP_CONTENT_TYPE_MAP(XX) +#undef XX + return ""; +} + +enum http_content_type http_content_type_enum_by_suffix(const char* str) { + if (!str || !*str) { + return CONTENT_TYPE_NONE; + } +#define XX(name, string, suffix) \ + if (strcmp(str, #suffix) == 0) { \ + return name; \ + } + HTTP_CONTENT_TYPE_MAP(XX) +#undef XX + return CONTENT_TYPE_UNDEFINED; +} diff --git a/external/libhv/libhv-1.3.2/http/httpdef.h b/external/libhv/libhv-1.3.2/http/httpdef.h new file mode 100644 index 0000000..3f25f54 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/httpdef.h @@ -0,0 +1,295 @@ +#ifndef HV_HTTP_DEF_H_ +#define HV_HTTP_DEF_H_ + +#include "hexport.h" + +#define DEFAULT_HTTP_PORT 80 +#define DEFAULT_HTTPS_PORT 443 + +enum http_version { HTTP_V1 = 1, HTTP_V2 = 2 }; +enum http_session_type { HTTP_CLIENT, HTTP_SERVER }; +enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH }; +enum http_parser_state { + HP_START_REQ_OR_RES, + HP_MESSAGE_BEGIN, + HP_URL, + HP_STATUS, + HP_HEADER_FIELD, + HP_HEADER_VALUE, + HP_HEADERS_COMPLETE, + HP_CHUNK_HEADER, + HP_BODY, + HP_CHUNK_COMPLETE, + HP_MESSAGE_COMPLETE, + HP_ERROR +}; + +// http_status +// XX(num, name, string) +#define HTTP_STATUS_MAP(XX) \ + XX(100, CONTINUE, Continue) \ + XX(101, SWITCHING_PROTOCOLS, Switching Protocols) \ + XX(102, PROCESSING, Processing) \ + XX(200, OK, OK) \ + XX(201, CREATED, Created) \ + XX(202, ACCEPTED, Accepted) \ + XX(203, NON_AUTHORITATIVE_INFORMATION, Non-Authoritative Information) \ + XX(204, NO_CONTENT, No Content) \ + XX(205, RESET_CONTENT, Reset Content) \ + XX(206, PARTIAL_CONTENT, Partial Content) \ + XX(207, MULTI_STATUS, Multi-Status) \ + XX(208, ALREADY_REPORTED, Already Reported) \ + XX(226, IM_USED, IM Used) \ + XX(300, MULTIPLE_CHOICES, Multiple Choices) \ + XX(301, MOVED_PERMANENTLY, Moved Permanently) \ + XX(302, FOUND, Found) \ + XX(303, SEE_OTHER, See Other) \ + XX(304, NOT_MODIFIED, Not Modified) \ + XX(305, USE_PROXY, Use Proxy) \ + XX(307, TEMPORARY_REDIRECT, Temporary Redirect) \ + XX(308, PERMANENT_REDIRECT, Permanent Redirect) \ + XX(400, BAD_REQUEST, Bad Request) \ + XX(401, UNAUTHORIZED, Unauthorized) \ + XX(402, PAYMENT_REQUIRED, Payment Required) \ + XX(403, FORBIDDEN, Forbidden) \ + XX(404, NOT_FOUND, Not Found) \ + XX(405, METHOD_NOT_ALLOWED, Method Not Allowed) \ + XX(406, NOT_ACCEPTABLE, Not Acceptable) \ + XX(407, PROXY_AUTHENTICATION_REQUIRED, Proxy Authentication Required) \ + XX(408, REQUEST_TIMEOUT, Request Timeout) \ + XX(409, CONFLICT, Conflict) \ + XX(410, GONE, Gone) \ + XX(411, LENGTH_REQUIRED, Length Required) \ + XX(412, PRECONDITION_FAILED, Precondition Failed) \ + XX(413, PAYLOAD_TOO_LARGE, Payload Too Large) \ + XX(414, URI_TOO_LONG, URI Too Long) \ + XX(415, UNSUPPORTED_MEDIA_TYPE, Unsupported Media Type) \ + XX(416, RANGE_NOT_SATISFIABLE, Range Not Satisfiable) \ + XX(417, EXPECTATION_FAILED, Expectation Failed) \ + XX(421, MISDIRECTED_REQUEST, Misdirected Request) \ + XX(422, UNPROCESSABLE_ENTITY, Unprocessable Entity) \ + XX(423, LOCKED, Locked) \ + XX(424, FAILED_DEPENDENCY, Failed Dependency) \ + XX(426, UPGRADE_REQUIRED, Upgrade Required) \ + XX(428, PRECONDITION_REQUIRED, Precondition Required) \ + XX(429, TOO_MANY_REQUESTS, Too Many Requests) \ + XX(431, REQUEST_HEADER_FIELDS_TOO_LARGE, Request Header Fields Too Large) \ + XX(451, UNAVAILABLE_FOR_LEGAL_REASONS, Unavailable For Legal Reasons) \ + XX(500, INTERNAL_SERVER_ERROR, Internal Server Error) \ + XX(501, NOT_IMPLEMENTED, Not Implemented) \ + XX(502, BAD_GATEWAY, Bad Gateway) \ + XX(503, SERVICE_UNAVAILABLE, Service Unavailable) \ + XX(504, GATEWAY_TIMEOUT, Gateway Timeout) \ + XX(505, HTTP_VERSION_NOT_SUPPORTED, HTTP Version Not Supported) \ + XX(506, VARIANT_ALSO_NEGOTIATES, Variant Also Negotiates) \ + XX(507, INSUFFICIENT_STORAGE, Insufficient Storage) \ + XX(508, LOOP_DETECTED, Loop Detected) \ + XX(510, NOT_EXTENDED, Not Extended) \ + XX(511, NETWORK_AUTHENTICATION_REQUIRED, Network Authentication Required) \ + +// HTTP_STATUS_##name +enum http_status { +#define XX(num, name, string) HTTP_STATUS_##name = num, + HTTP_STATUS_MAP(XX) +#undef XX + HTTP_CUSTOM_STATUS +}; + +#define HTTP_STATUS_IS_REDIRECT(status) \ + ( \ + (status) == HTTP_STATUS_MOVED_PERMANENTLY || \ + (status) == HTTP_STATUS_FOUND || \ + (status) == HTTP_STATUS_SEE_OTHER || \ + (status) == HTTP_STATUS_TEMPORARY_REDIRECT || \ + (status) == HTTP_STATUS_PERMANENT_REDIRECT \ + ) + +// http_mehtod +// XX(num, name, string) +#define HTTP_METHOD_MAP(XX) \ + XX(0, DELETE, DELETE) \ + XX(1, GET, GET) \ + XX(2, HEAD, HEAD) \ + XX(3, POST, POST) \ + XX(4, PUT, PUT) \ + /* pathological */ \ + XX(5, CONNECT, CONNECT) \ + XX(6, OPTIONS, OPTIONS) \ + XX(7, TRACE, TRACE) \ + /* WebDAV */ \ + XX(8, COPY, COPY) \ + XX(9, LOCK, LOCK) \ + XX(10, MKCOL, MKCOL) \ + XX(11, MOVE, MOVE) \ + XX(12, PROPFIND, PROPFIND) \ + XX(13, PROPPATCH, PROPPATCH) \ + XX(14, SEARCH, SEARCH) \ + XX(15, UNLOCK, UNLOCK) \ + XX(16, BIND, BIND) \ + XX(17, REBIND, REBIND) \ + XX(18, UNBIND, UNBIND) \ + XX(19, ACL, ACL) \ + /* subversion */ \ + XX(20, REPORT, REPORT) \ + XX(21, MKACTIVITY, MKACTIVITY) \ + XX(22, CHECKOUT, CHECKOUT) \ + XX(23, MERGE, MERGE) \ + /* upnp */ \ + XX(24, MSEARCH, M-SEARCH) \ + XX(25, NOTIFY, NOTIFY) \ + XX(26, SUBSCRIBE, SUBSCRIBE) \ + XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \ + /* RFC-5789 */ \ + XX(28, PATCH, PATCH) \ + XX(29, PURGE, PURGE) \ + /* CalDAV */ \ + XX(30, MKCALENDAR, MKCALENDAR) \ + /* RFC-2068, section 19.6.1.2 */ \ + XX(31, LINK, LINK) \ + XX(32, UNLINK, UNLINK) \ + /* icecast */ \ + XX(33, SOURCE, SOURCE) \ + +// HTTP_##name +enum http_method { +#define XX(num, name, string) HTTP_##name = num, + HTTP_METHOD_MAP(XX) +#undef XX + HTTP_CUSTOM_METHOD +}; + +// MIME: https://www.iana.org/assignments/media-types/media-types.xhtml +// XX(name, mime, suffix) +#define MIME_TYPE_TEXT_MAP(XX) \ + XX(TEXT_PLAIN, text/plain, txt) \ + XX(TEXT_HTML, text/html, html) \ + XX(TEXT_CSS, text/css, css) \ + XX(TEXT_CSV, text/csv, csv) \ + XX(TEXT_MARKDOWN, text/markdown, md) \ + XX(TEXT_EVENT_STREAM, text/event-stream, sse) \ + +#define MIME_TYPE_APPLICATION_MAP(XX) \ + XX(APPLICATION_JAVASCRIPT, application/javascript, js) \ + XX(APPLICATION_JSON, application/json, json) \ + XX(APPLICATION_XML, application/xml, xml) \ + XX(APPLICATION_URLENCODED, application/x-www-form-urlencoded, kv) \ + XX(APPLICATION_OCTET_STREAM,application/octet-stream, bin) \ + XX(APPLICATION_ZIP, application/zip, zip) \ + XX(APPLICATION_GZIP, application/gzip, gzip) \ + XX(APPLICATION_7Z, application/x-7z-compressed, 7z) \ + XX(APPLICATION_RAR, application/x-rar-compressed, rar) \ + XX(APPLICATION_PDF, application/pdf, pdf) \ + XX(APPLICATION_RTF, application/rtf, rtf) \ + XX(APPLICATION_GRPC, application/grpc, grpc) \ + XX(APPLICATION_WASM, application/wasm, wasm) \ + XX(APPLICATION_JAR, application/java-archive, jar) \ + XX(APPLICATION_XHTML, application/xhtml+xml, xhtml) \ + XX(APPLICATION_ATOM, application/atom+xml, atom) \ + XX(APPLICATION_RSS, application/rss+xml, rss) \ + XX(APPLICATION_WORD, application/msword, doc) \ + XX(APPLICATION_EXCEL, application/vnd.ms-excel, xls) \ + XX(APPLICATION_PPT, application/vnd.ms-powerpoint, ppt) \ + XX(APPLICATION_EOT, application/vnd.ms-fontobject, eot) \ + XX(APPLICATION_M3U8, application/vnd.apple.mpegurl, m3u8) \ + XX(APPLICATION_DOCX, application/vnd.openxmlformats-officedocument.wordprocessingml.document, docx) \ + XX(APPLICATION_XLSX, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, xlsx) \ + XX(APPLICATION_PPTX, application/vnd.openxmlformats-officedocument.presentationml.presentation, pptx) \ + +#define MIME_TYPE_MULTIPART_MAP(XX) \ + XX(MULTIPART_FORM_DATA, multipart/form-data, mp) \ + +#define MIME_TYPE_IMAGE_MAP(XX) \ + XX(IMAGE_JPEG, image/jpeg, jpg) \ + XX(IMAGE_PNG, image/png, png) \ + XX(IMAGE_GIF, image/gif, gif) \ + XX(IMAGE_ICO, image/x-icon, ico) \ + XX(IMAGE_BMP, image/x-ms-bmp, bmp) \ + XX(IMAGE_SVG, image/svg+xml, svg) \ + XX(IMAGE_TIFF, image/tiff, tiff) \ + XX(IMAGE_WEBP, image/webp, webp) \ + +#define MIME_TYPE_VIDEO_MAP(XX) \ + XX(VIDEO_MP4, video/mp4, mp4) \ + XX(VIDEO_FLV, video/x-flv, flv) \ + XX(VIDEO_M4V, video/x-m4v, m4v) \ + XX(VIDEO_MNG, video/x-mng, mng) \ + XX(VIDEO_TS, video/mp2t, ts) \ + XX(VIDEO_MPEG, video/mpeg, mpeg) \ + XX(VIDEO_WEBM, video/webm, webm) \ + XX(VIDEO_MOV, video/quicktime, mov) \ + XX(VIDEO_3GPP, video/3gpp, 3gpp) \ + XX(VIDEO_AVI, video/x-msvideo, avi) \ + XX(VIDEO_WMV, video/x-ms-wmv, wmv) \ + XX(VIDEO_ASF, video/x-ms-asf, asf) \ + +#define MIME_TYPE_AUDIO_MAP(XX) \ + XX(AUDIO_MP3, audio/mpeg, mp3) \ + XX(AUDIO_OGG, audio/ogg, ogg) \ + XX(AUDIO_M4A, audio/x-m4a, m4a) \ + XX(AUDIO_AAC, audio/aac, aac) \ + XX(AUDIO_PCMA, audio/PCMA, pcma) \ + XX(AUDIO_OPUS, audio/opus, opus) \ + +#define MIME_TYPE_FONT_MAP(XX) \ + XX(FONT_TTF, font/ttf, ttf) \ + XX(FONT_OTF, font/otf, otf) \ + XX(FONT_WOFF, font/woff, woff) \ + XX(FONT_WOFF2, font/woff2, woff2) \ + +#define HTTP_CONTENT_TYPE_MAP(XX) \ + MIME_TYPE_TEXT_MAP(XX) \ + MIME_TYPE_APPLICATION_MAP(XX) \ + MIME_TYPE_MULTIPART_MAP(XX) \ + MIME_TYPE_IMAGE_MAP(XX) \ + MIME_TYPE_VIDEO_MAP(XX) \ + MIME_TYPE_AUDIO_MAP(XX) \ + MIME_TYPE_FONT_MAP(XX) \ + +#define X_WWW_FORM_URLENCODED APPLICATION_URLENCODED // for compatibility + +enum http_content_type { +#define XX(name, string, suffix) name, + CONTENT_TYPE_NONE = 0, + + CONTENT_TYPE_TEXT = 100, + MIME_TYPE_TEXT_MAP(XX) + + CONTENT_TYPE_APPLICATION = 200, + MIME_TYPE_APPLICATION_MAP(XX) + + CONTENT_TYPE_MULTIPART = 300, + MIME_TYPE_MULTIPART_MAP(XX) + + CONTENT_TYPE_IMAGE = 400, + MIME_TYPE_IMAGE_MAP(XX) + + CONTENT_TYPE_VIDEO = 500, + MIME_TYPE_VIDEO_MAP(XX) + + CONTENT_TYPE_AUDIO = 600, + MIME_TYPE_AUDIO_MAP(XX) + + CONTENT_TYPE_FONT = 700, + MIME_TYPE_FONT_MAP(XX) + + CONTENT_TYPE_UNDEFINED = 1000 +#undef XX +}; + +BEGIN_EXTERN_C + +HV_EXPORT const char* http_status_str(enum http_status status); +HV_EXPORT const char* http_method_str(enum http_method method); +HV_EXPORT const char* http_content_type_str(enum http_content_type type); + +HV_EXPORT enum http_status http_status_enum(const char* str); +HV_EXPORT enum http_method http_method_enum(const char* str); +HV_EXPORT enum http_content_type http_content_type_enum(const char* str); + +HV_EXPORT const char* http_content_type_suffix(enum http_content_type type); +HV_EXPORT const char* http_content_type_str_by_suffix(const char* suffix); +HV_EXPORT enum http_content_type http_content_type_enum_by_suffix(const char* suffix); + +END_EXTERN_C + +#endif // HV_HTTP_DEF_H_ diff --git a/external/libhv/libhv-1.3.2/http/multipart_parser.c b/external/libhv/libhv-1.3.2/http/multipart_parser.c new file mode 100644 index 0000000..6a2e550 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/multipart_parser.c @@ -0,0 +1,308 @@ +/* Based on node-formidable by Felix Geisendörfer + * Igor Afonov - afonov@gmail.com - 2012 + * MIT License - http://www.opensource.org/licenses/mit-license.php + */ + +#include "multipart_parser.h" + +#include +#include +#include + +static void multipart_log(const char * format, ...) +{ +#ifdef DEBUG_MULTIPART + va_list args; + va_start(args, format); + + fprintf(stderr, "[HTTP_MULTIPART_PARSER] %s:%d: ", __FILE__, __LINE__); + vfprintf(stderr, format, args); + fprintf(stderr, "\n"); + + va_end(args); +#endif +} + +#define NOTIFY_CB(FOR) \ +do { \ + if (p->settings->on_##FOR) { \ + if (p->settings->on_##FOR(p) != 0) { \ + return i; \ + } \ + } \ +} while (0) + +#define EMIT_DATA_CB(FOR, ptr, len) \ +do { \ + if (p->settings->on_##FOR) { \ + if (p->settings->on_##FOR(p, ptr, len) != 0) { \ + return i; \ + } \ + } \ +} while (0) + + +#define LF 10 +#define CR 13 + +struct multipart_parser { + void * data; + + size_t index; + size_t boundary_length; + + unsigned char state; + + const multipart_parser_settings* settings; + + char* lookbehind; + char multipart_boundary[1]; +}; + +enum state { + s_uninitialized = 1, + s_start, + s_start_boundary, + s_header_field_start, + s_header_field, + s_headers_almost_done, + s_header_value_start, + s_header_value, + s_header_value_almost_done, + s_part_data_start, + s_part_data, + s_part_data_almost_boundary, + s_part_data_boundary, + s_part_data_almost_end, + s_part_data_end, + s_part_data_final_hyphen, + s_end +}; + +multipart_parser* multipart_parser_init + (const char *boundary, const multipart_parser_settings* settings) { + + multipart_parser* p = (multipart_parser*)malloc(sizeof(multipart_parser) + + strlen(boundary) + + strlen(boundary) + 9); + + strcpy(p->multipart_boundary, boundary); + p->boundary_length = strlen(boundary); + + p->lookbehind = (p->multipart_boundary + p->boundary_length + 1); + + p->index = 0; + p->state = s_start; + p->settings = settings; + + return p; +} + +void multipart_parser_free(multipart_parser* p) { + free(p); +} + +void multipart_parser_set_data(multipart_parser *p, void *data) { + p->data = data; +} + +void *multipart_parser_get_data(multipart_parser *p) { + return p->data; +} + +size_t multipart_parser_execute(multipart_parser* p, const char *buf, size_t len) { + size_t i = 0; + size_t mark = 0; + char c, cl; + int is_last = 0; + + while(i < len) { + c = buf[i]; + is_last = (i == (len - 1)); + switch (p->state) { + case s_start: + multipart_log("s_start"); + p->index = 0; + p->state = s_start_boundary; + + /* fallthrough */ + case s_start_boundary: + multipart_log("s_start_boundary"); + if (p->index == p->boundary_length) { + if (c != CR) { + return i; + } + p->index++; + break; + } else if (p->index == (p->boundary_length + 1)) { + if (c != LF) { + return i; + } + p->index = 0; + NOTIFY_CB(part_data_begin); + p->state = s_header_field_start; + break; + } + if (c != p->multipart_boundary[p->index]) { + return i; + } + p->index++; + break; + + case s_header_field_start: + multipart_log("s_header_field_start"); + mark = i; + p->state = s_header_field; + + /* fallthrough */ + case s_header_field: + multipart_log("s_header_field"); + if (c == CR) { + p->state = s_headers_almost_done; + break; + } + + if (c == ':') { + EMIT_DATA_CB(header_field, buf + mark, i - mark); + p->state = s_header_value_start; + break; + } + + cl = tolower(c); + if ((c != '-') && (cl < 'a' || cl > 'z')) { + multipart_log("invalid character in header name"); + return i; + } + if (is_last) + EMIT_DATA_CB(header_field, buf + mark, (i - mark) + 1); + break; + + case s_headers_almost_done: + multipart_log("s_headers_almost_done"); + if (c != LF) { + return i; + } + + p->state = s_part_data_start; + break; + + case s_header_value_start: + multipart_log("s_header_value_start"); + if (c == ' ') { + break; + } + + mark = i; + p->state = s_header_value; + + /* fallthrough */ + case s_header_value: + multipart_log("s_header_value"); + if (c == CR) { + EMIT_DATA_CB(header_value, buf + mark, i - mark); + p->state = s_header_value_almost_done; + break; + } + if (is_last) + EMIT_DATA_CB(header_value, buf + mark, (i - mark) + 1); + break; + + case s_header_value_almost_done: + multipart_log("s_header_value_almost_done"); + if (c != LF) { + return i; + } + p->state = s_header_field_start; + break; + + case s_part_data_start: + multipart_log("s_part_data_start"); + NOTIFY_CB(headers_complete); + mark = i; + p->state = s_part_data; + + /* fallthrough */ + case s_part_data: + multipart_log("s_part_data"); + if (c == CR) { + EMIT_DATA_CB(part_data, buf + mark, i - mark); + mark = i; + p->state = s_part_data_almost_boundary; + p->lookbehind[0] = CR; + break; + } + if (is_last) + EMIT_DATA_CB(part_data, buf + mark, (i - mark) + 1); + break; + + case s_part_data_almost_boundary: + multipart_log("s_part_data_almost_boundary"); + if (c == LF) { + p->state = s_part_data_boundary; + p->lookbehind[1] = LF; + p->index = 0; + break; + } + EMIT_DATA_CB(part_data, p->lookbehind, 1); + p->state = s_part_data; + mark = i --; + break; + + case s_part_data_boundary: + multipart_log("s_part_data_boundary"); + if (p->multipart_boundary[p->index] != c) { + EMIT_DATA_CB(part_data, p->lookbehind, 2 + p->index); + p->state = s_part_data; + mark = i --; + break; + } + p->lookbehind[2 + p->index] = c; + if ((++ p->index) == p->boundary_length) { + NOTIFY_CB(part_data_end); + p->state = s_part_data_almost_end; + } + break; + + case s_part_data_almost_end: + multipart_log("s_part_data_almost_end"); + if (c == '-') { + p->state = s_part_data_final_hyphen; + break; + } + if (c == CR) { + p->state = s_part_data_end; + break; + } + return i; + + case s_part_data_final_hyphen: + multipart_log("s_part_data_final_hyphen"); + if (c == '-') { + NOTIFY_CB(body_end); + p->state = s_end; + break; + } + return i; + + case s_part_data_end: + multipart_log("s_part_data_end"); + if (c == LF) { + p->state = s_header_field_start; + NOTIFY_CB(part_data_begin); + break; + } + return i; + + case s_end: + multipart_log("s_end: %02X", (int) c); + break; + + default: + multipart_log("Multipart parser unrecoverable error"); + return 0; + } + ++ i; + } + + return len; +} diff --git a/external/libhv/libhv-1.3.2/http/multipart_parser.h b/external/libhv/libhv-1.3.2/http/multipart_parser.h new file mode 100644 index 0000000..05429d7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/multipart_parser.h @@ -0,0 +1,48 @@ +/* Based on node-formidable by Felix Geisendörfer + * Igor Afonov - afonov@gmail.com - 2012 + * MIT License - http://www.opensource.org/licenses/mit-license.php + */ +#ifndef _multipart_parser_h +#define _multipart_parser_h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include + +typedef struct multipart_parser multipart_parser; +typedef struct multipart_parser_settings multipart_parser_settings; +typedef struct multipart_parser_state multipart_parser_state; + +typedef int (*multipart_data_cb) (multipart_parser*, const char *at, size_t length); +typedef int (*multipart_notify_cb) (multipart_parser*); + +struct multipart_parser_settings { + multipart_data_cb on_header_field; + multipart_data_cb on_header_value; + multipart_data_cb on_part_data; + + multipart_notify_cb on_part_data_begin; + multipart_notify_cb on_headers_complete; + multipart_notify_cb on_part_data_end; + multipart_notify_cb on_body_end; +}; + +multipart_parser* multipart_parser_init + (const char *boundary, const multipart_parser_settings* settings); + +void multipart_parser_free(multipart_parser* p); + +size_t multipart_parser_execute(multipart_parser* p, const char *buf, size_t len); + +void multipart_parser_set_data(multipart_parser* p, void* data); +void * multipart_parser_get_data(multipart_parser* p); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/external/libhv/libhv-1.3.2/http/server/FileCache.cpp b/external/libhv/libhv-1.3.2/http/server/FileCache.cpp new file mode 100644 index 0000000..c3b49bc --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/FileCache.cpp @@ -0,0 +1,157 @@ +#include "FileCache.h" + +#include "herr.h" +#include "hscope.h" +#include "htime.h" +#include "hlog.h" + +#include "httpdef.h" // import http_content_type_str_by_suffix +#include "http_page.h" // import make_index_of_page + +#define ETAG_FMT "\"%zx-%zx\"" + +file_cache_ptr FileCache::Open(const char* filepath, OpenParam* param) { + std::lock_guard locker(mutex_); + file_cache_ptr fc = Get(filepath); + bool modified = false; + if (fc) { + time_t now = time(NULL); + if (now - fc->stat_time > stat_interval) { + modified = fc->is_modified(); + fc->stat_time = now; + fc->stat_cnt++; + } + if (param->need_read) { + if (!modified && fc->is_complete()) { + param->need_read = false; + } + } + } + if (fc == NULL || modified || param->need_read) { + int flags = O_RDONLY; +#ifdef O_BINARY + flags |= O_BINARY; +#endif + int fd = open(filepath, flags); + if (fd < 0) { +#ifdef OS_WIN + // NOTE: open(dir) return -1 on windows + if (!hv_isdir(filepath)) { + param->error = ERR_OPEN_FILE; + return NULL; + } +#else + param->error = ERR_OPEN_FILE; + return NULL; +#endif + } + defer(if (fd > 0) { close(fd); }) + if (fc == NULL) { + struct stat st; + if (fd > 0) { + fstat(fd, &st); + } else { + stat(filepath, &st); + } + if (S_ISREG(st.st_mode) || + (S_ISDIR(st.st_mode) && + filepath[strlen(filepath)-1] == '/')) { + fc = std::make_shared(); + fc->filepath = filepath; + fc->st = st; + time(&fc->open_time); + fc->stat_time = fc->open_time; + fc->stat_cnt = 1; + cached_files[filepath] = fc; + } + else { + param->error = ERR_MISMATCH; + return NULL; + } + } + if (S_ISREG(fc->st.st_mode)) { + param->filesize = fc->st.st_size; + // FILE + if (param->need_read) { + if (fc->st.st_size > param->max_read) { + param->error = ERR_OVER_LIMIT; + return NULL; + } + fc->resize_buf(fc->st.st_size); + int nread = read(fd, fc->filebuf.base, fc->filebuf.len); + if (nread != fc->filebuf.len) { + hloge("Failed to read file: %s", filepath); + param->error = ERR_READ_FILE; + return NULL; + } + } + const char* suffix = strrchr(filepath, '.'); + if (suffix) { + http_content_type content_type = http_content_type_enum_by_suffix(suffix+1); + if (content_type == TEXT_HTML) { + fc->content_type = "text/html; charset=utf-8"; + } else if (content_type == TEXT_PLAIN) { + fc->content_type = "text/plain; charset=utf-8"; + } else { + fc->content_type = http_content_type_str_by_suffix(suffix+1); + } + } + } + else if (S_ISDIR(fc->st.st_mode)) { + // DIR + std::string page; + make_index_of_page(filepath, page, param->path); + fc->resize_buf(page.size()); + memcpy(fc->filebuf.base, page.c_str(), page.size()); + fc->content_type = "text/html; charset=utf-8"; + } + gmtime_fmt(fc->st.st_mtime, fc->last_modified); + snprintf(fc->etag, sizeof(fc->etag), ETAG_FMT, (size_t)fc->st.st_mtime, (size_t)fc->st.st_size); + } + return fc; +} + +bool FileCache::Close(const char* filepath) { + std::lock_guard locker(mutex_); + auto iter = cached_files.find(filepath); + if (iter != cached_files.end()) { + iter = cached_files.erase(iter); + return true; + } + return false; +} + +bool FileCache::Close(const file_cache_ptr& fc) { + std::lock_guard locker(mutex_); + auto iter = cached_files.begin(); + while (iter != cached_files.end()) { + if (iter->second == fc) { + iter = cached_files.erase(iter); + return true; + } else { + ++iter; + } + } + return false; +} + +file_cache_ptr FileCache::Get(const char* filepath) { + auto iter = cached_files.find(filepath); + if (iter != cached_files.end()) { + return iter->second; + } + return NULL; +} + +void FileCache::RemoveExpiredFileCache() { + std::lock_guard locker(mutex_); + time_t now = time(NULL); + auto iter = cached_files.begin(); + while (iter != cached_files.end()) { + if (now - iter->second->stat_time > expired_time) { + iter = cached_files.erase(iter); + } else { + ++iter; + } + } +} diff --git a/external/libhv/libhv-1.3.2/http/server/FileCache.h b/external/libhv/libhv-1.3.2/http/server/FileCache.h new file mode 100644 index 0000000..bb4ab90 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/FileCache.h @@ -0,0 +1,96 @@ +#ifndef HV_FILE_CACHE_H_ +#define HV_FILE_CACHE_H_ + +#include +#include +#include +#include + +#include "hbuf.h" +#include "hstring.h" + +#define HTTP_HEADER_MAX_LENGTH 1024 // 1K +#define FILE_CACHE_MAX_SIZE (1 << 22) // 4M + +typedef struct file_cache_s { + std::string filepath; + struct stat st; + time_t open_time; + time_t stat_time; + uint32_t stat_cnt; + HBuf buf; // http_header + file_content + hbuf_t filebuf; + hbuf_t httpbuf; + char last_modified[64]; + char etag[64]; + std::string content_type; + + file_cache_s() { + stat_cnt = 0; + } + + bool is_modified() { + time_t mtime = st.st_mtime; + stat(filepath.c_str(), &st); + return mtime != st.st_mtime; + } + + bool is_complete() { + return filebuf.len == st.st_size; + } + + void resize_buf(int filesize) { + buf.resize(HTTP_HEADER_MAX_LENGTH + filesize); + filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH; + filebuf.len = filesize; + } + + void prepend_header(const char* header, int len) { + if (len > HTTP_HEADER_MAX_LENGTH) return; + httpbuf.base = filebuf.base - len; + httpbuf.len = len + filebuf.len; + memcpy(httpbuf.base, header, len); + } +} file_cache_t; + +typedef std::shared_ptr file_cache_ptr; +// filepath => file_cache_ptr +typedef std::map FileCacheMap; + +class FileCache { +public: + FileCacheMap cached_files; + std::mutex mutex_; + int stat_interval; + int expired_time; + + FileCache() { + stat_interval = 10; // s + expired_time = 60; // s + } + + struct OpenParam { + bool need_read; + int max_read; + const char* path; + size_t filesize; + int error; + + OpenParam() { + need_read = true; + max_read = FILE_CACHE_MAX_SIZE; + path = "/"; + filesize = 0; + error = 0; + } + }; + file_cache_ptr Open(const char* filepath, OpenParam* param); + bool Close(const char* filepath); + bool Close(const file_cache_ptr& fc); + void RemoveExpiredFileCache(); + +protected: + file_cache_ptr Get(const char* filepath); +}; + +#endif // HV_FILE_CACHE_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpContext.h b/external/libhv/libhv-1.3.2/http/server/HttpContext.h new file mode 100644 index 0000000..5c3defd --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpContext.h @@ -0,0 +1,213 @@ +#ifndef HV_HTTP_CONTEXT_H_ +#define HV_HTTP_CONTEXT_H_ + +#include "hexport.h" +#include "HttpMessage.h" +#include "HttpResponseWriter.h" + +namespace hv { + +struct HttpService; +struct HV_EXPORT HttpContext { + HttpService* service; + HttpRequestPtr request; + HttpResponsePtr response; + HttpResponseWriterPtr writer; + void* userdata; + + HttpContext() { + service = NULL; + userdata = NULL; + } + + // HttpRequest aliases + // return request->xxx + std::string ip() { + return request->client_addr.ip; + } + + int port() { + return request->client_addr.port; + } + + http_method method() { + return request->method; + } + + std::string url() { + return request->url; + } + + std::string path() { + return request->Path(); + } + + std::string fullpath() { + return request->FullPath(); + } + + std::string host() { + return request->Host(); + } + + const http_headers& headers() { + return request->headers; + } + + std::string header(const char* key, const std::string& defvalue = hv::empty_string) { + return request->GetHeader(key, defvalue); + } + + const hv::QueryParams& params() { + return request->query_params; + } + + std::string param(const char* key, const std::string& defvalue = hv::empty_string) { + return request->GetParam(key, defvalue); + } + + const HttpCookie& cookie(const char* name) { + return request->GetCookie(name); + } + + int length() { + return request->ContentLength(); + } + + http_content_type type() { + return request->ContentType(); + } + + bool is(http_content_type content_type) { + return request->ContentType() == content_type; + } + + bool is(const char* content_type) { + return request->ContentType() == http_content_type_enum(content_type); + } + + std::string& body() { + return request->body; + } + +#ifndef WITHOUT_HTTP_CONTENT + // Content-Type: application/json + const hv::Json& json() { + return request->GetJson(); + } + + // Content-Type: multipart/form-data + const hv::MultiPart& form() { + return request->GetForm(); + } + std::string form(const char* name, const std::string& defvalue = hv::empty_string) { + return request->GetFormData(name, defvalue); + } + + // Content-Type: application/x-www-form-urlencoded + const hv::KeyValue& urlencoded() { + return request->GetUrlEncoded(); + } + std::string urlencoded(const char* key, const std::string& defvalue = hv::empty_string) { + return request->GetUrlEncoded(key, defvalue); + } + + // T=[bool, int, int64_t, float, double] + template + T get(const char* key, T defvalue = 0) { + return request->Get(key, defvalue); + } + std::string get(const char* key, const std::string& defvalue = hv::empty_string) { + return request->GetString(key, defvalue); + } +#endif + + // HttpResponse aliases + // response->xxx = xxx + void setStatus(http_status status) { + response->status_code = status; + } + + void setContentType(http_content_type type) { + response->content_type = type; + } + + void setContentType(const char* type) { + response->content_type = http_content_type_enum(type); + } + + void setHeader(const char* key, const std::string& value) { + response->SetHeader(key, value); + if (stricmp(key, "Content-Type") == 0) { + setContentType(value.c_str()); + } + } + + void setCookie(const HttpCookie& cookie) { + response->AddCookie(cookie); + } + + void setBody(const std::string& body) { + response->body = body; + } + + // response->sendXxx + int send() { + if (writer) { + writer->End(); + } + return response->status_code; + } + + int send(const std::string& str, http_content_type type = APPLICATION_JSON) { + response->content_type = type; + response->body = str; + return send(); + } + + int sendString(const std::string& str) { + response->String(str); + return send(); + } + + int sendData(void* data, int len, bool nocopy = true) { + response->Data(data, len, nocopy); + return send(); + } + + int sendFile(const char* filepath) { + response->File(filepath); + return send(); + } + +#ifndef WITHOUT_HTTP_CONTENT + // T=[bool, int, int64_t, float, double, string] + template + void set(const char* key, const T& value) { + response->Set(key, value); + } + + // @see HttpMessage::Json + // @usage https://github.com/nlohmann/json + template + int sendJson(const T& t) { + response->Json(t); + return send(); + } +#endif + + int redirect(const std::string& location, http_status status = HTTP_STATUS_FOUND) { + response->Redirect(location, status); + return send(); + } + + int close() { + return writer ? writer->close(true) : -1; + } +}; + +} // end namespace hv + +typedef std::shared_ptr HttpContextPtr; + +#endif // HV_HTTP_CONTEXT_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpHandler.cpp b/external/libhv/libhv-1.3.2/http/server/HttpHandler.cpp new file mode 100644 index 0000000..dc081a0 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpHandler.cpp @@ -0,0 +1,1135 @@ +#include "HttpHandler.h" + +#include "hversion.h" +#include "herr.h" +#include "hlog.h" +#include "htime.h" +#include "hurl.h" +#include "hasync.h" // import hv::async for http_async_handler + +#include "httpdef.h" +#include "http2def.h" +#include "wsdef.h" + +#include "http_page.h" + +#include "EventLoop.h" // import hv::setInterval +using namespace hv; + +#define MIN_HTTP_REQUEST "GET / HTTP/1.1\r\n\r\n" +#define MIN_HTTP_REQUEST_LEN 14 // exclude CRLF + +#define HTTP_100_CONTINUE_RESPONSE "HTTP/1.1 100 Continue\r\n\r\n" +#define HTTP_100_CONTINUE_RESPONSE_LEN 25 +#define HTTP_200_CONNECT_RESPONSE "HTTP/1.1 200 Connection established\r\n\r\n" +#define HTTP_200_CONNECT_RESPONSE_LEN 39 + +HttpHandler::HttpHandler(hio_t* io) : + protocol(HttpHandler::UNKNOWN), + state(WANT_RECV), + error(0), + // flags + ssl(0), + keepalive(1), + upgrade(0), + proxy(0), + proxy_connected(0), + forward_proxy(0), + reverse_proxy(0), + ip{'\0'}, + port(0), + pid(0), + tid(0), + // for http + io(io), + service(NULL), + api_handler(NULL), + // for websocket + ws_service(NULL), + last_send_ping_time(0), + last_recv_pong_time(0), + // for sendfile + files(NULL), + file(NULL), + // for proxy + proxy_port(0) +{ + // Init(); +} + +HttpHandler::~HttpHandler() { + Close(); +} + +bool HttpHandler::Init(int http_version) { + parser.reset(HttpParser::New(HTTP_SERVER, (enum http_version)http_version)); + if (parser == NULL) { + return false; + } + req = std::make_shared(); + resp = std::make_shared(); + if(http_version == 1) { + protocol = HTTP_V1; + } else if (http_version == 2) { + protocol = HTTP_V2; + resp->http_major = req->http_major = 2; + resp->http_minor = req->http_minor = 0; + } + if (io) { + hloop_t* loop = hevent_loop(io); + pid = hloop_pid(loop); + tid = hloop_tid(loop); + writer = std::make_shared(io, resp); + writer->status = hv::SocketChannel::CONNECTED; + } else { + pid = hv_getpid(); + tid = hv_gettid(); + } + parser->InitRequest(req.get()); + // NOTE: hook http_cb + req->http_cb = [this](HttpMessage* msg, http_parser_state state, const char* data, size_t size) { + if (this->state == WANT_CLOSE) return; + switch (state) { + case HP_HEADERS_COMPLETE: + if (this->error != 0) return; + onHeadersComplete(); + break; + case HP_BODY: + if (this->error != 0) return; + onBody(data, size); + break; + case HP_MESSAGE_COMPLETE: + onMessageComplete(); + break; + default: + break; + } + }; + return true; +} + +void HttpHandler::Reset() { + state = WANT_RECV; + error = 0; + req->Reset(); + resp->Reset(); + ctx = NULL; + api_handler = NULL; + closeFile(); + if (writer) { + writer->Begin(); + writer->onwrite = NULL; + writer->onclose = NULL; + } + parser->InitRequest(req.get()); +} + +void HttpHandler::Close() { + if (writer) { + writer->status = hv::SocketChannel::DISCONNECTED; + } + + if (api_handler && api_handler->state_handler) { + if (parser && !parser->IsComplete()) { + api_handler->state_handler(context(), HP_ERROR, NULL, 0); + } + return; + } + + // close proxy + closeProxy(); + + // close file + closeFile(); + + // onclose + if (protocol == HttpHandler::WEBSOCKET) { + WebSocketOnClose(); + } else { + if (writer && writer->onclose) { + writer->onclose(); + } + } +} + +bool HttpHandler::SwitchHTTP2() { + parser.reset(HttpParser::New(HTTP_SERVER, ::HTTP_V2)); + if (parser == NULL) { + return false; + } + protocol = HTTP_V2; + resp->http_major = req->http_major = 2; + resp->http_minor = req->http_minor = 0; + parser->InitRequest(req.get()); + return true; +} + +bool HttpHandler::SwitchWebSocket() { + if(!io) return false; + + protocol = WEBSOCKET; + ws_parser = std::make_shared(); + ws_channel = std::make_shared(io, WS_SERVER); + ws_parser->onMessage = [this](int opcode, const std::string& msg){ + ws_channel->opcode = (enum ws_opcode)opcode; + switch(opcode) { + case WS_OPCODE_CLOSE: + ws_channel->close(); + break; + case WS_OPCODE_PING: + // printf("recv ping\n"); + // printf("send pong\n"); + ws_channel->send(msg, WS_OPCODE_PONG); + break; + case WS_OPCODE_PONG: + // printf("recv pong\n"); + this->last_recv_pong_time = gethrtime_us(); + break; + case WS_OPCODE_TEXT: + case WS_OPCODE_BINARY: + // onmessage + if (ws_service && ws_service->onmessage) { + ws_service->onmessage(ws_channel, msg); + } + break; + default: + break; + } + }; + // NOTE: cancel keepalive timer, judge alive by heartbeat. + ws_channel->setKeepaliveTimeout(0); + if (ws_service && ws_service->ping_interval > 0) { + int ping_interval = MAX(ws_service->ping_interval, 1000); + ws_channel->setHeartbeat(ping_interval, [this](){ + if (last_recv_pong_time < last_send_ping_time) { + hlogw("[%s:%d] websocket no pong!", ip, port); + ws_channel->close(); + } else { + // printf("send ping\n"); + ws_channel->sendPing(); + last_send_ping_time = gethrtime_us(); + } + }); + } + return true; +} + +const HttpContextPtr& HttpHandler::context() { + if (!ctx) { + ctx = std::make_shared(); + ctx->service = service; + ctx->request = req; + ctx->response = resp; + ctx->writer = writer; + } + return ctx; +} + +int HttpHandler::customHttpHandler(const http_handler& handler) { + return invokeHttpHandler(&handler); +} + +int HttpHandler::invokeHttpHandler(const http_handler* handler) { + int status_code = HTTP_STATUS_NOT_IMPLEMENTED; + if (handler->sync_handler) { + // NOTE: sync_handler run on IO thread + status_code = handler->sync_handler(req.get(), resp.get()); + } else if (handler->async_handler) { + // NOTE: async_handler run on hv::async threadpool + hv::async(std::bind(handler->async_handler, req, writer)); + status_code = HTTP_STATUS_NEXT; + } else if (handler->ctx_handler) { + // NOTE: ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing. + status_code = handler->ctx_handler(context()); + } else if (handler->state_handler) { + status_code = handler->state_handler(context(), HP_MESSAGE_COMPLETE, NULL, 0); + } + return status_code; +} + +void HttpHandler::onHeadersComplete() { + // printf("onHeadersComplete\n"); + handleRequestHeaders(); + + HttpRequest* pReq = req.get(); + if (service && service->pathHandlers.size() != 0) { + service->GetRoute(pReq, &api_handler); + } + + if (api_handler && api_handler->state_handler) { + api_handler->state_handler(context(), HP_HEADERS_COMPLETE, NULL, 0); + return; + } + + if (proxy) { + handleProxy(); + return; + } + + // Expect: 100-continue + handleExpect100(); +} + +void HttpHandler::onBody(const char* data, size_t size) { + if (api_handler && api_handler->state_handler) { + api_handler->state_handler(context(), HP_BODY, data, size); + return; + } + + if (proxy && proxy_connected) { + if (io) hio_write_upstream(io, (void*)data, size); + return; + } + + req->body.append(data, size); + return; +} + +void HttpHandler::onMessageComplete() { + // printf("onMessageComplete\n"); + int status_code = HTTP_STATUS_OK; + + if (error) { + SendHttpStatusResponse(resp->status_code); + return; + } + + if (proxy) { + if (proxy_connected) Reset(); + return; + } + + addResponseHeaders(); + + // upgrade ? handleUpgrade : HandleHttpRequest + if (upgrade) { + auto iter_upgrade = req->headers.find("upgrade"); + if (iter_upgrade != req->headers.end()) { + handleUpgrade(iter_upgrade->second.c_str()); + status_code = resp->status_code; + } + } else { + status_code = HandleHttpRequest(); + if (status_code != HTTP_STATUS_NEXT) { + SendHttpResponse(); + } + } + + // access log + if (service && service->enable_access_log) { + hlogi("[%ld-%ld][%s:%d][%s %s]=>[%d %s]", + pid, tid, ip, port, + http_method_str(req->method), req->path.c_str(), + resp->status_code, resp->status_message()); + } + + if (status_code != HTTP_STATUS_NEXT) { + // keepalive ? Reset : Close + if (keepalive) { + Reset(); + } else { + state = WANT_CLOSE; + } + } +} + +void HttpHandler::handleRequestHeaders() { + HttpRequest* pReq = req.get(); + pReq->scheme = ssl ? "https" : "http"; + pReq->client_addr.ip = ip; + pReq->client_addr.port = port; + + // keepalive + keepalive = pReq->IsKeepAlive(); + + // upgrade + upgrade = pReq->IsUpgrade(); + + // proxy + proxy = forward_proxy = reverse_proxy = 0; + if (hv::startswith(pReq->url, "http")) { + // forward proxy + proxy = forward_proxy = 1; + } + else if (pReq->method == HTTP_CONNECT) { + // proxy tunnel + // CONNECT ip:port HTTP/1.1\r\n + pReq->url = "https://" + pReq->url; + proxy = forward_proxy = 1; + keepalive = true; + } + + // printf("url=%s\n", pReq->url.c_str()); + pReq->ParseUrl(); + + if (proxy) { + // Proxy-Connection + auto iter = pReq->headers.find("Proxy-Connection"); + if (iter != pReq->headers.end()) { + const char* keepalive_value = iter->second.c_str(); + if (stricmp(keepalive_value, "keep-alive") == 0) { + keepalive = true; + } + else if (stricmp(keepalive_value, "close") == 0) { + keepalive = false; + } + else if (stricmp(keepalive_value, "upgrade") == 0) { + keepalive = true; + } + } + } + else { + // reverse proxy + std::string proxy_url = service->GetProxyUrl(pReq->path.c_str()); + if (!proxy_url.empty()) { + pReq->url = proxy_url; + proxy = reverse_proxy = 1; + } + } + + // TODO: rewrite url +} + +void HttpHandler::handleExpect100() { + // Expect: 100-continue + auto iter = req->headers.find("Expect"); + if (iter != req->headers.end() && + stricmp(iter->second.c_str(), "100-continue") == 0) { + if (io) hio_write(io, HTTP_100_CONTINUE_RESPONSE, HTTP_100_CONTINUE_RESPONSE_LEN); + } +} + +void HttpHandler::addResponseHeaders() { + HttpResponse* pResp = resp.get(); + // Server: + static char s_Server[64] = {'\0'}; + if (s_Server[0] == '\0') { + snprintf(s_Server, sizeof(s_Server), "httpd/%s", hv_version()); + } + pResp->headers["Server"] = s_Server; + + // Connection: + pResp->headers["Connection"] = keepalive ? "keep-alive" : "close"; +} + +int HttpHandler::HandleHttpRequest() { + // preprocessor -> middleware -> processor -> postprocessor + HttpRequest* pReq = req.get(); + HttpResponse* pResp = resp.get(); + + // NOTE: Not all users want to parse body, we comment it out. + // pReq->ParseBody(); + + int status_code = pResp->status_code; + if (status_code != HTTP_STATUS_OK) { + goto postprocessor; + } + +preprocessor: + state = HANDLE_BEGIN; + if (service->preprocessor) { + status_code = customHttpHandler(service->preprocessor); + if (status_code != HTTP_STATUS_NEXT) { + goto postprocessor; + } + } + +middleware: + for (const auto& middleware : service->middleware) { + status_code = customHttpHandler(middleware); + if (status_code != HTTP_STATUS_NEXT) { + goto postprocessor; + } + } + +processor: + if (service->processor) { + status_code = customHttpHandler(service->processor); + } else { + status_code = defaultRequestHandler(); + } + +postprocessor: + if (status_code >= 100 && status_code < 600) { + pResp->status_code = (http_status)status_code; + if (pResp->status_code >= 400 && pResp->body.size() == 0 && pReq->method != HTTP_HEAD) { + if (service->errorHandler) { + customHttpHandler(service->errorHandler); + } else { + defaultErrorHandler(); + } + } + } + if (fc) { + pResp->content = fc->filebuf.base; + pResp->content_length = fc->filebuf.len; + pResp->headers["Content-Type"] = fc->content_type; + pResp->headers["Last-Modified"] = fc->last_modified; + pResp->headers["Etag"] = fc->etag; + } + if (service->postprocessor) { + customHttpHandler(service->postprocessor); + } + + if (writer && writer->state != hv::HttpResponseWriter::SEND_BEGIN) { + status_code = HTTP_STATUS_NEXT; + } + if (status_code == HTTP_STATUS_NEXT) { + state = HANDLE_CONTINUE; + } else { + state = HANDLE_END; + } + return status_code; +} + +int HttpHandler::defaultRequestHandler() { + int status_code = HTTP_STATUS_OK; + + if (api_handler) { + status_code = invokeHttpHandler(api_handler); + } + else if (req->method == HTTP_GET || req->method == HTTP_HEAD) { + // static handler + if (service->staticHandler) { + status_code = customHttpHandler(service->staticHandler); + } + else if (service->staticDirs.size() > 0) { + status_code = defaultStaticHandler(); + } + else { + status_code = HTTP_STATUS_NOT_FOUND; + } + } + else { + // Not Implemented + status_code = HTTP_STATUS_NOT_IMPLEMENTED; + } + + return status_code; +} + +int HttpHandler::defaultStaticHandler() { + // file service + std::string path = req->Path(); + const char* req_path = path.c_str(); + // path safe check + if (req_path[0] != '/' || strstr(req_path, "/..") || strstr(req_path, "\\..")) { + return HTTP_STATUS_BAD_REQUEST; + } + + std::string filepath; + bool is_dir = path.back() == '/' && + service->index_of.size() > 0 && + hv_strstartswith(req_path, service->index_of.c_str()); + if (is_dir) { + filepath = service->document_root + path; + } else { + filepath = service->GetStaticFilepath(req_path); + } + if (filepath.empty()) { + return HTTP_STATUS_NOT_FOUND; + } + + int status_code = HTTP_STATUS_OK; + // Range: + bool has_range = false; + long from, to = 0; + if (req->GetRange(from, to)) { + has_range = true; + if (openFile(filepath.c_str()) != 0) { + return HTTP_STATUS_NOT_FOUND; + } + long total = file->size(); + if (to == 0 || to >= total) to = total - 1; + file->seek(from); + status_code = HTTP_STATUS_PARTIAL_CONTENT; + resp->status_code = HTTP_STATUS_PARTIAL_CONTENT; + resp->content_length = to - from + 1; + resp->SetContentTypeByFilename(filepath.c_str()); + resp->SetRange(from, to, total); + if(resp->content_length < service->max_file_cache_size) { + // read into body directly + int nread = file->readrange(resp->body, from, to); + closeFile(); + if (nread != resp->content_length) { + resp->content_length = 0; + resp->body.clear(); + return HTTP_STATUS_INTERNAL_SERVER_ERROR; + } + } + else { + if (service->largeFileHandler) { + status_code = customHttpHandler(service->largeFileHandler); + } else { + status_code = defaultLargeFileHandler(); + } + } + return status_code; + } + + // FileCache + FileCache::OpenParam param; + param.max_read = service->max_file_cache_size; + param.need_read = !(req->method == HTTP_HEAD || has_range); + param.path = req_path; + if (files) { + fc = files->Open(filepath.c_str(), ¶m); + } + if (fc == NULL) { + if (param.error == ERR_OVER_LIMIT) { + if (service->largeFileHandler) { + status_code = customHttpHandler(service->largeFileHandler); + } else { + status_code = defaultLargeFileHandler(); + } + } else { + status_code = HTTP_STATUS_NOT_FOUND; + } + } + else { + // Not Modified + auto iter = req->headers.find("if-not-match"); + if (iter != req->headers.end() && + strcmp(iter->second.c_str(), fc->etag) == 0) { + fc = NULL; + return HTTP_STATUS_NOT_MODIFIED; + } + + iter = req->headers.find("if-modified-since"); + if (iter != req->headers.end() && + strcmp(iter->second.c_str(), fc->last_modified) == 0) { + fc = NULL; + return HTTP_STATUS_NOT_MODIFIED; + } + } + return status_code; +} + +int HttpHandler::defaultLargeFileHandler() { + if (!writer) return HTTP_STATUS_NOT_IMPLEMENTED; + if (!isFileOpened()) { + std::string filepath = service->GetStaticFilepath(req->Path().c_str()); + if (filepath.empty() || openFile(filepath.c_str()) != 0) { + return HTTP_STATUS_NOT_FOUND; + } + resp->content_length = file->size(); + resp->SetContentTypeByFilename(filepath.c_str()); + } + if (service->limit_rate == 0) { + // forbidden to send large file + resp->content_length = 0; + resp->status_code = HTTP_STATUS_FORBIDDEN; + } else { + size_t bufsize = 40960; // 40K + file->buf.resize(bufsize); + if (service->limit_rate < 0) { + // unlimited: sendFile when writable + writer->onwrite = [this](HBuf* buf) { + if (writer->isWriteComplete()) { + sendFile(); + } + }; + } else { + // limit_rate=40KB/s interval_ms=1000 + // limit_rate=500KB/s interval_ms=80 + int interval_ms = file->buf.len * 1000 / 1024 / service->limit_rate; + // limit_rate=40MB/s interval_m=1: 40KB/ms = 40MB/s = 320Mbps + if (interval_ms == 0) interval_ms = 1; + // printf("limit_rate=%dKB/s interval_ms=%d\n", service->limit_rate, interval_ms); + file->timer = setInterval(interval_ms, std::bind(&HttpHandler::sendFile, this)); + } + } + writer->EndHeaders(); + return HTTP_STATUS_UNFINISHED; +} + +int HttpHandler::defaultErrorHandler() { + // error page + if (service->error_page.size() != 0) { + std::string filepath = service->document_root + '/' + service->error_page; + if (files) { + // cache and load error page + FileCache::OpenParam param; + fc = files->Open(filepath.c_str(), ¶m); + } + } + // status page + if (fc == NULL && resp->body.size() == 0) { + resp->content_type = TEXT_HTML; + make_http_status_page(resp->status_code, resp->body); + } + return 0; +} + +int HttpHandler::FeedRecvData(const char* data, size_t len) { + if (protocol == HttpHandler::UNKNOWN) { + int http_version = 1; +#if WITH_NGHTTP2 + if (strncmp(data, HTTP2_MAGIC, MIN(len, HTTP2_MAGIC_LEN)) == 0) { + http_version = 2; + } +#else + // check request-line + if (len < MIN_HTTP_REQUEST_LEN) { + hloge("[%s:%d] http request-line too small", ip, port); + error = ERR_REQUEST; + return -1; + } + for (int i = 0; i < MIN_HTTP_REQUEST_LEN; ++i) { + if (!IS_GRAPH(data[i])) { + hloge("[%s:%d] http request-line not plain", ip, port); + error = ERR_REQUEST; + return -1; + } + } +#endif + if (!Init(http_version)) { + hloge("[%s:%d] unsupported HTTP%d", ip, port, http_version); + error = ERR_INVALID_PROTOCOL; + return -1; + } + } + + int nfeed = 0; + switch (protocol) { + case HttpHandler::HTTP_V1: + case HttpHandler::HTTP_V2: + if (state != WANT_RECV) { + Reset(); + } + nfeed = parser->FeedRecvData(data, len); + // printf("FeedRecvData %d=>%d\n", (int)len, nfeed); + if (nfeed != len) { + hloge("[%s:%d] http parse error: %s", ip, port, parser->StrError(parser->GetError())); + error = ERR_PARSE; + return -1; + } + break; + case HttpHandler::WEBSOCKET: + nfeed = ws_parser->FeedRecvData(data, len); + if (nfeed != len) { + hloge("[%s:%d] websocket parse error!", ip, port); + error = ERR_PARSE; + return -1; + } + break; + default: + hloge("[%s:%d] unknown protocol", ip, port); + error = ERR_INVALID_PROTOCOL; + return -1; + } + + if (state == WANT_CLOSE) return 0; + return error ? -1 : nfeed; +} + +int HttpHandler::GetSendData(char** data, size_t* len) { + if (state == HANDLE_CONTINUE) { + return 0; + } + + HttpRequest* pReq = req.get(); + HttpResponse* pResp = resp.get(); + + if (protocol == HTTP_V1) { + switch(state) { + case WANT_RECV: + if (parser->IsComplete()) state = WANT_SEND; + else return 0; + case HANDLE_END: + state = WANT_SEND; + case WANT_SEND: + state = SEND_HEADER; + case SEND_HEADER: + { + size_t content_length = 0; + const char* content = NULL; + // HEAD + if (pReq->method == HTTP_HEAD) { + if (fc) { + pResp->headers["Accept-Ranges"] = "bytes"; + pResp->headers["Content-Length"] = hv::to_string(fc->st.st_size); + } else { + pResp->headers["Content-Type"] = "text/html"; + pResp->headers["Content-Length"] = "0"; + } + state = SEND_DONE; + goto return_nobody; + } + // File service + if (fc) { + // FileCache + // NOTE: no copy filebuf, more efficient + header = pResp->Dump(true, false); + fc->prepend_header(header.c_str(), header.size()); + *data = fc->httpbuf.base; + *len = fc->httpbuf.len; + state = SEND_DONE; + return *len; + } + // API service + content_length = pResp->ContentLength(); + content = (const char*)pResp->Content(); + if (content) { + if (content_length > (1 << 20)) { + state = SEND_BODY; + goto return_header; + } else { + // NOTE: header+body in one package if <= 1M + header = pResp->Dump(true, false); + header.append(content, content_length); + state = SEND_DONE; + goto return_header; + } + } else { + state = SEND_DONE; + goto return_header; + } +return_nobody: + pResp->content_length = 0; +return_header: + if (header.empty()) header = pResp->Dump(true, false); + *data = (char*)header.c_str(); + *len = header.size(); + return *len; + } + case SEND_BODY: + { + *data = (char*)pResp->Content(); + *len = pResp->ContentLength(); + state = SEND_DONE; + return *len; + } + case SEND_DONE: + { + // NOTE: remove file cache if > FILE_CACHE_MAX_SIZE + if (fc && fc->filebuf.len > FILE_CACHE_MAX_SIZE) { + files->Close(fc); + } + fc = NULL; + header.clear(); + return 0; + } + default: + return 0; + } + } else if (protocol == HTTP_V2) { + int ret = parser->GetSendData(data, len); + if (ret == 0) state = SEND_DONE; + return ret; + } + return 0; +} + +int HttpHandler::SendHttpResponse(bool submit) { + if (!io || !parser) return -1; + char* data = NULL; + size_t len = 0, total_len = 0; + if (submit) parser->SubmitResponse(resp.get()); + while (GetSendData(&data, &len)) { + // printf("GetSendData %d\n", (int)len); + if (data && len) { + hio_write(io, data, len); + total_len += len; + } + } + return total_len; +} + +int HttpHandler::SendHttpStatusResponse(http_status status_code) { + if (state > WANT_SEND) return 0; + resp->status_code = status_code; + addResponseHeaders(); + HandleHttpRequest(); + state = WANT_SEND; + return SendHttpResponse(); +} + +//------------------sendfile-------------------------------------- +int HttpHandler::openFile(const char* filepath) { + closeFile(); + file = new LargeFile; + file->timer = INVALID_TIMER_ID; + return file->open(filepath, "rb"); +} + +bool HttpHandler::isFileOpened() { + return file && file->isopen(); +} + +int HttpHandler::sendFile() { + if (!writer || !writer->isWriteComplete() || + !isFileOpened() || + file->buf.len == 0 || + resp->content_length == 0) { + return -1; + } + + int readbytes = MIN(file->buf.len, resp->content_length); + size_t nread = file->read(file->buf.base, readbytes); + if (nread <= 0) { + hloge("read file error!"); + error = ERR_READ_FILE; + writer->close(true); + return nread; + } + int nwrite = writer->WriteBody(file->buf.base, nread); + if (nwrite < 0) { + // disconnectd + writer->close(true); + return nwrite; + } + resp->content_length -= nread; + if (resp->content_length == 0) { + writer->End(); + closeFile(); + } + return nread; +} + +void HttpHandler::closeFile() { + if (file) { + if (file->timer != INVALID_TIMER_ID) { + killTimer(file->timer); + file->timer = INVALID_TIMER_ID; + } + delete file; + file = NULL; + } +} + +//------------------upgrade-------------------------------------- +int HttpHandler::handleUpgrade(const char* upgrade_protocol) { + hlogi("[%s:%d] Upgrade: %s", ip, port, upgrade_protocol); + + // websocket + if (stricmp(upgrade_protocol, "websocket") == 0) { + return upgradeWebSocket(); + } + + // h2/h2c + if (strnicmp(upgrade_protocol, "h2", 2) == 0) { + return upgradeHTTP2(); + } + + hloge("[%s:%d] unsupported Upgrade: %s", ip, port, upgrade_protocol); + return SetError(ERR_INVALID_PROTOCOL); +} + +int HttpHandler::upgradeWebSocket() { + /* + HTTP/1.1 101 Switching Protocols + Connection: Upgrade + Upgrade: websocket + Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= + */ + resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS; + resp->headers["Connection"] = "Upgrade"; + resp->headers["Upgrade"] = "websocket"; + + // Sec-WebSocket-Accept: + auto iter_key = req->headers.find(SEC_WEBSOCKET_KEY); + if (iter_key != req->headers.end()) { + char ws_accept[32] = {0}; + ws_encode_key(iter_key->second.c_str(), ws_accept); + resp->headers[SEC_WEBSOCKET_ACCEPT] = ws_accept; + } + + // Sec-WebSocket-Protocol: + auto iter_protocol = req->headers.find(SEC_WEBSOCKET_PROTOCOL); + if (iter_protocol != req->headers.end()) { + hv::StringList subprotocols = hv::split(iter_protocol->second, ','); + if (subprotocols.size() > 0) { + hlogw("%s: %s => just select first protocol %s", SEC_WEBSOCKET_PROTOCOL, iter_protocol->second.c_str(), subprotocols[0].c_str()); + resp->headers[SEC_WEBSOCKET_PROTOCOL] = subprotocols[0]; + } + } + + SendHttpResponse(); + + if (!SwitchWebSocket()) { + hloge("[%s:%d] unsupported websocket", ip, port); + return SetError(ERR_INVALID_PROTOCOL); + } + + // onopen + WebSocketOnOpen(); + return 0; +} + +int HttpHandler::upgradeHTTP2() { + /* + HTTP/1.1 101 Switching Protocols + Connection: Upgrade + Upgrade: h2c + */ + resp->status_code = HTTP_STATUS_SWITCHING_PROTOCOLS; + resp->headers["Connection"] = "Upgrade"; + resp->headers["Upgrade"] = "h2c"; + + SendHttpResponse(); + + if (!SwitchHTTP2()) { + hloge("[%s:%d] unsupported HTTP2", ip, port); + return SetError(ERR_INVALID_PROTOCOL); + } + + // NOTE: send HTTP2_SETTINGS frame + SendHttpResponse(false); + + return 0; +} + +//------------------proxy-------------------------------------- +int HttpHandler::handleProxy() { + if (forward_proxy) { + return handleForwardProxy(); + } + + if (reverse_proxy) { + return handleReverseProxy(); + } + + return 0; +} + +int HttpHandler::handleForwardProxy() { + if (service && service->enable_forward_proxy) { + return connectProxy(req->url); + } else { + hlogw("Forbidden to forward proxy %s", req->url.c_str()); + SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN); + } + return 0; +} + +int HttpHandler::handleReverseProxy() { + return connectProxy(req->url); +} + +int HttpHandler::connectProxy(const std::string& strUrl) { + if (!io) return ERR_NULL_POINTER; + + HUrl url; + url.parse(strUrl); + hlogi("[%s:%d] proxy_pass %s", ip, port, strUrl.c_str()); + + if (proxy_connected) { + if (url.host == proxy_host && url.port == proxy_port) { + // reuse keepalive connection + sendProxyRequest(); + return 0; + } else { + // detach and close previous connection + hio_t* upstream_io = hio_get_upstream(io); + if (upstream_io) { + hio_setcb_close(upstream_io, NULL); + closeProxy(); + } + } + } + + if (forward_proxy && !service->IsTrustProxy(url.host.c_str())) { + hlogw("Forbidden to proxy %s", url.host.c_str()); + SetError(HTTP_STATUS_FORBIDDEN, HTTP_STATUS_FORBIDDEN); + return 0; + } + + hloop_t* loop = hevent_loop(io); + proxy = 1; + proxy_host = url.host; + proxy_port = url.port; + hio_t* upstream_io = hio_create_socket(loop, proxy_host.c_str(), proxy_port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (upstream_io == NULL) { + return SetError(ERR_SOCKET, HTTP_STATUS_BAD_GATEWAY); + } + if (url.scheme == "https") { + hio_enable_ssl(upstream_io); + } + hevent_set_userdata(upstream_io, this); + hio_setup_upstream(io, upstream_io); + hio_setcb_connect(upstream_io, HttpHandler::onProxyConnect); + hio_setcb_close(upstream_io, HttpHandler::onProxyClose); + if (service->proxy_connect_timeout > 0) { + hio_set_connect_timeout(upstream_io, service->proxy_connect_timeout); + } + if (service->proxy_read_timeout > 0) { + hio_set_read_timeout(io, service->proxy_read_timeout); + } + if (service->proxy_write_timeout > 0) { + hio_set_write_timeout(io, service->proxy_write_timeout); + } + hio_connect(upstream_io); + // NOTE: wait upstream_io connected then start read + hio_read_stop(io); + return 0; +} + +int HttpHandler::closeProxy() { + if (proxy && proxy_connected) { + proxy_connected = 0; + if (io) hio_close_upstream(io); + } + return 0; +} + +int HttpHandler::sendProxyRequest() { + if (!io || !proxy_connected) return -1; + + req->headers.erase("Host"); + req->FillHost(proxy_host.c_str(), proxy_port); + req->headers.erase("Proxy-Connection"); + req->headers["Connection"] = keepalive ? "keep-alive" : "close"; + req->headers["X-Real-IP"] = ip; + // NOTE: send head + received body + std::string msg = req->Dump(true, true); + // printf("%s\n", msg.c_str()); + req->Reset(); + + hio_write_upstream(io, (void*)msg.c_str(), msg.size()); + if (parser->IsComplete()) state = WANT_SEND; + return msg.size(); +} + +void HttpHandler::onProxyConnect(hio_t* upstream_io) { + // printf("onProxyConnect\n"); + HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io); + hio_t* io = hio_get_upstream(upstream_io); + assert(handler != NULL && io != NULL); + handler->proxy_connected = 1; + + if (handler->req->method == HTTP_CONNECT) { + // handler->resp->status_code = HTTP_STATUS_OK; + // handler->SendHttpResponse(); + hio_write(io, HTTP_200_CONNECT_RESPONSE, HTTP_200_CONNECT_RESPONSE_LEN); + handler->state = SEND_DONE; + // NOTE: recv request then upstream + hio_setcb_read(io, hio_write_upstream); + } else { + handler->sendProxyRequest(); + } + + // NOTE: start recv request continue then upstream + if (handler->upgrade) hio_setcb_read(io, hio_write_upstream); + hio_read_start(io); + // NOTE: start recv response then upstream + hio_setcb_read(upstream_io, hio_write_upstream); + hio_read_start(upstream_io); +} + +void HttpHandler::onProxyClose(hio_t* upstream_io) { + // printf("onProxyClose\n"); + HttpHandler* handler = (HttpHandler*)hevent_userdata(upstream_io); + if (handler == NULL) return; + handler->proxy_connected = 0; + + hevent_set_userdata(upstream_io, NULL); + + int error = hio_error(upstream_io); + if (error == ETIMEDOUT) { + handler->SendHttpStatusResponse(HTTP_STATUS_GATEWAY_TIMEOUT); + } + + handler->error = error; + hio_close_upstream(upstream_io); +} diff --git a/external/libhv/libhv-1.3.2/http/server/HttpHandler.h b/external/libhv/libhv-1.3.2/http/server/HttpHandler.h new file mode 100644 index 0000000..b3363ee --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpHandler.h @@ -0,0 +1,186 @@ +#ifndef HV_HTTP_HANDLER_H_ +#define HV_HTTP_HANDLER_H_ + +#include "HttpService.h" +#include "HttpParser.h" +#include "FileCache.h" + +#include "WebSocketServer.h" +#include "WebSocketParser.h" + +class HttpHandler { +public: + enum ProtocolType { + UNKNOWN, + HTTP_V1, + HTTP_V2, + WEBSOCKET, + } protocol; + + enum State { + WANT_RECV, + HANDLE_BEGIN, + HANDLE_CONTINUE, + HANDLE_END, + WANT_SEND, + SEND_HEADER, + SEND_BODY, + SEND_DONE, + WANT_CLOSE, + } state; + + // errno + int error; + + // flags + unsigned ssl :1; + unsigned keepalive :1; + unsigned upgrade :1; + unsigned proxy :1; + unsigned proxy_connected :1; + unsigned forward_proxy :1; + unsigned reverse_proxy :1; + + // peeraddr + char ip[64]; + int port; + + // for log + long pid; + long tid; + + // for http + hio_t *io; + HttpService *service; + HttpRequestPtr req; + HttpResponsePtr resp; + HttpResponseWriterPtr writer; + HttpParserPtr parser; + HttpContextPtr ctx; + http_handler* api_handler; + + // for GetSendData + std::string header; + // std::string body; + + // for websocket + WebSocketService* ws_service; + WebSocketChannelPtr ws_channel; + WebSocketParserPtr ws_parser; + uint64_t last_send_ping_time; + uint64_t last_recv_pong_time; + + // for sendfile + FileCache *files; + file_cache_ptr fc; // cache small file + struct LargeFile : public HFile { + HBuf buf; + uint64_t timer; + } *file; // for large file + + // for proxy + std::string proxy_host; + int proxy_port; + + HttpHandler(hio_t* io = NULL); + ~HttpHandler(); + + bool Init(int http_version = 1); + void Reset(); + void Close(); + + /* @workflow: + * HttpServer::on_recv -> HttpHandler::FeedRecvData -> Init -> HttpParser::InitRequest -> HttpRequest::http_cb -> + * onHeadersComplete -> proxy ? handleProxy -> connectProxy : + * onMessageComplete -> upgrade ? handleUpgrade : HandleHttpRequest -> HttpParser::SubmitResponse -> + * SendHttpResponse -> while(GetSendData) hio_write -> + * keepalive ? Reset : Close -> hio_close + * + * @return + * == len: ok + * == 0: WANT_CLOSE + * < 0: error + */ + int FeedRecvData(const char* data, size_t len); + + /* @workflow: + * preprocessor -> middleware -> processor -> postprocessor + * + * @return status_code + * == 0: HANDLE_CONTINUE + * != 0: HANDLE_END + */ + int HandleHttpRequest(); + + int GetSendData(char** data, size_t* len); + + int SendHttpResponse(bool submit = true); + int SendHttpStatusResponse(http_status status_code); + + // HTTP2 + bool SwitchHTTP2(); + + // websocket + bool SwitchWebSocket(); + void WebSocketOnOpen() { + ws_channel->status = hv::SocketChannel::CONNECTED; + if (ws_service && ws_service->onopen) { + ws_service->onopen(ws_channel, req); + } + } + void WebSocketOnClose() { + ws_channel->status = hv::SocketChannel::DISCONNECTED; + if (ws_service && ws_service->onclose) { + ws_service->onclose(ws_channel); + } + } + + int SetError(int error_code, http_status status_code = HTTP_STATUS_BAD_REQUEST) { + error = error_code; + if (resp) resp->status_code = status_code; + return error; + } + +private: + const HttpContextPtr& context(); + void handleRequestHeaders(); + // Expect: 100-continue + void handleExpect100(); + void addResponseHeaders(); + + // http_cb + void onHeadersComplete(); + void onBody(const char* data, size_t size); + void onMessageComplete(); + + // default handlers + int defaultRequestHandler(); + int defaultStaticHandler(); + int defaultLargeFileHandler(); + int defaultErrorHandler(); + int customHttpHandler(const http_handler& handler); + int invokeHttpHandler(const http_handler* handler); + + // sendfile + int openFile(const char* filepath); + int sendFile(); + void closeFile(); + bool isFileOpened(); + + // upgrade + int handleUpgrade(const char* upgrade_protocol); + int upgradeWebSocket(); + int upgradeHTTP2(); + + // proxy + int handleProxy(); + int handleForwardProxy(); + int handleReverseProxy(); + int connectProxy(const std::string& url); + int closeProxy(); + int sendProxyRequest(); + static void onProxyConnect(hio_t* upstream_io); + static void onProxyClose(hio_t* upstream_io); +}; + +#endif // HV_HTTP_HANDLER_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.cpp b/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.cpp new file mode 100644 index 0000000..4560790 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.cpp @@ -0,0 +1,16 @@ +#include "HttpMiddleware.h" +#include "HttpService.h" + +BEGIN_NAMESPACE_HV + +int HttpMiddleware::CORS(HttpRequest* req, HttpResponse* resp) { + resp->headers["Access-Control-Allow-Origin"] = req->GetHeader("Origin", "*"); + if (req->method == HTTP_OPTIONS) { + resp->headers["Access-Control-Allow-Methods"] = req->GetHeader("Access-Control-Request-Method", "OPTIONS, HEAD, GET, POST, PUT, DELETE, PATCH"); + resp->headers["Access-Control-Allow-Headers"] = req->GetHeader("Access-Control-Request-Headers", "Content-Type"); + return HTTP_STATUS_NO_CONTENT; + } + return HTTP_STATUS_NEXT; +} + +END_NAMESPACE_HV diff --git a/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.h b/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.h new file mode 100644 index 0000000..d310143 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpMiddleware.h @@ -0,0 +1,16 @@ +#ifndef HV_HTTP_MIDDLEWARE_H_ +#define HV_HTTP_MIDDLEWARE_H_ + +#include "hexport.h" +#include "HttpContext.h" + +BEGIN_NAMESPACE_HV + +class HttpMiddleware { +public: + static int CORS(HttpRequest* req, HttpResponse* resp); +}; + +END_NAMESPACE_HV + +#endif // HV_HTTP_MIDDLEWARE_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.cpp b/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.cpp new file mode 100644 index 0000000..6f0cd60 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.cpp @@ -0,0 +1,113 @@ +#include "HttpResponseWriter.h" + +namespace hv { + +int HttpResponseWriter::EndHeaders(const char* key /* = NULL */, const char* value /* = NULL */) { + if (state != SEND_BEGIN) return -1; + if (key && value) { + response->SetHeader(key, value); + } + std::string headers = response->Dump(true, false); + state = SEND_HEADER; + return write(headers); +} + +int HttpResponseWriter::WriteChunked(const char* buf, int len /* = -1 */) { + int ret = 0; + if (len == -1) len = strlen(buf); + if (state == SEND_BEGIN) { + EndHeaders("Transfer-Encoding", "chunked"); + } + char chunked_header[64]; + int chunked_header_len = snprintf(chunked_header, sizeof(chunked_header), "%x\r\n", len); + write(chunked_header, chunked_header_len); + if (buf && len) { + state = SEND_CHUNKED; + ret = write(buf, len); + } else { + state = SEND_CHUNKED_END; + } + write("\r\n", 2); + return ret; +} + +int HttpResponseWriter::WriteBody(const char* buf, int len /* = -1 */) { + if (response->IsChunked()) { + return WriteChunked(buf, len); + } + + if (len == -1) len = strlen(buf); + if (state == SEND_BEGIN) { + response->body.append(buf, len); + return len; + } else { + state = SEND_BODY; + return write(buf, len); + } +} + +int HttpResponseWriter::WriteResponse(HttpResponse* resp) { + if (resp == NULL) { + response->status_code = HTTP_STATUS_INTERNAL_SERVER_ERROR; + return 0; + } + bool is_dump_headers = state == SEND_BEGIN ? true : false; + std::string msg = resp->Dump(is_dump_headers, true); + state = SEND_BODY; + return write(msg); +} + +int HttpResponseWriter::SSEvent(const std::string& data, const char* event /* = "message" */) { + if (state == SEND_BEGIN) { + EndHeaders("Content-Type", "text/event-stream"); + } + std::string msg; + msg = "event: "; msg += event; msg += "\n"; + msg += "data: "; msg += data; msg += "\n\n"; + state = SEND_BODY; + return write(msg); +} + +int HttpResponseWriter::End(const char* buf /* = NULL */, int len /* = -1 */) { + if (end == SEND_END) return 0; + end = SEND_END; + + if (!isConnected()) { + return -1; + } + + int ret = 0; + bool keepAlive = response->IsKeepAlive(); + if (state == SEND_CHUNKED) { + if (buf) { + ret = WriteChunked(buf, len); + } + if (state == SEND_CHUNKED) { + EndChunked(); + } + } else { + if (buf) { + ret = WriteBody(buf, len); + } + bool is_dump_headers = true; + bool is_dump_body = true; + if (state == SEND_HEADER) { + is_dump_headers = false; + } else if (state == SEND_BODY) { + is_dump_headers = false; + is_dump_body = false; + } + if (is_dump_body) { + std::string msg = response->Dump(is_dump_headers, is_dump_body); + state = SEND_BODY; + ret = write(msg); + } + } + + if (!keepAlive) { + close(true); + } + return ret; +} + +} diff --git a/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.h b/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.h new file mode 100644 index 0000000..195fba7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpResponseWriter.h @@ -0,0 +1,100 @@ +#ifndef HV_HTTP_RESPONSE_WRITER_H_ +#define HV_HTTP_RESPONSE_WRITER_H_ + +#include "Channel.h" +#include "HttpMessage.h" + +namespace hv { + +class HV_EXPORT HttpResponseWriter : public SocketChannel { +public: + HttpResponsePtr response; + enum State { + SEND_BEGIN = 0, + SEND_HEADER, + SEND_BODY, + SEND_CHUNKED, + SEND_CHUNKED_END, + SEND_END, + } state: 8, end: 8; + HttpResponseWriter(hio_t* io, const HttpResponsePtr& resp) + : SocketChannel(io) + , response(resp) + , state(SEND_BEGIN) + , end(SEND_BEGIN) + {} + ~HttpResponseWriter() {} + + // Begin -> End + // Begin -> WriteResponse -> End + // Begin -> WriteStatus -> WriteHeader -> WriteBody -> End + // Begin -> EndHeaders("Content-Type", "text/event-stream") -> write -> write -> ... -> close + // Begin -> EndHeaders("Content-Length", content_length) -> WriteBody -> WriteBody -> ... -> End + // Begin -> EndHeaders("Transfer-Encoding", "chunked") -> WriteChunked -> WriteChunked -> ... -> End + + int Begin() { + state = end = SEND_BEGIN; + return 0; + } + + int WriteStatus(http_status status_codes) { + response->status_code = status_codes; + return 0; + } + + int WriteHeader(const char* key, const char* value) { + response->SetHeader(key, value); + return 0; + } + + template + int WriteHeader(const char* key, T num) { + response->SetHeader(key, hv::to_string(num)); + return 0; + } + + int WriteCookie(const HttpCookie& cookie) { + response->cookies.push_back(cookie); + return 0; + } + + int EndHeaders(const char* key = NULL, const char* value = NULL); + + template + int EndHeaders(const char* key, T num) { + std::string value = hv::to_string(num); + return EndHeaders(key, value.c_str()); + } + + int WriteChunked(const char* buf, int len = -1); + + int WriteChunked(const std::string& str) { + return WriteChunked(str.c_str(), str.size()); + } + + int EndChunked() { + return WriteChunked(NULL, 0); + } + + int WriteBody(const char* buf, int len = -1); + + int WriteBody(const std::string& str) { + return WriteBody(str.c_str(), str.size()); + } + + int WriteResponse(HttpResponse* resp); + + int SSEvent(const std::string& data, const char* event = "message"); + + int End(const char* buf = NULL, int len = -1); + + int End(const std::string& str) { + return End(str.c_str(), str.size()); + } +}; + +} + +typedef std::shared_ptr HttpResponseWriterPtr; + +#endif // HV_HTTP_RESPONSE_WRITER_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpServer.cpp b/external/libhv/libhv-1.3.2/http/server/HttpServer.cpp new file mode 100644 index 0000000..b2d4902 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpServer.cpp @@ -0,0 +1,280 @@ +#include "HttpServer.h" + +#include "hmain.h" // import master_workers_run +#include "herr.h" +#include "hlog.h" +#include "htime.h" + +#include "EventLoop.h" +using namespace hv; + +#include "HttpHandler.h" + +static void on_accept(hio_t* io); +static void on_recv(hio_t* io, void* _buf, int readbytes); +static void on_close(hio_t* io); + +struct HttpServerPrivdata { + std::vector loops; + std::vector threads; + std::mutex mutex_; + std::shared_ptr service; + FileCache filecache; +}; + +static void on_recv(hio_t* io, void* buf, int readbytes) { + // printf("on_recv fd=%d readbytes=%d\n", hio_fd(io), readbytes); + HttpHandler* handler = (HttpHandler*)hevent_userdata(io); + assert(handler != NULL); + + int nfeed = handler->FeedRecvData((const char*)buf, readbytes); + if (nfeed != readbytes) { + hio_close(io); + return; + } +} + +static void on_close(hio_t* io) { + HttpHandler* handler = (HttpHandler*)hevent_userdata(io); + if (handler == NULL) return; + + hevent_set_userdata(io, NULL); + delete handler; + + EventLoop* loop = currentThreadEventLoop; + if (loop) { + --loop->connectionNum; + } +} + +static void on_accept(hio_t* io) { + http_server_t* server = (http_server_t*)hevent_userdata(io); + HttpService* service = server->service; + /* + printf("on_accept connfd=%d\n", hio_fd(io)); + char localaddrstr[SOCKADDR_STRLEN] = {0}; + char peeraddrstr[SOCKADDR_STRLEN] = {0}; + printf("accept connfd=%d [%s] <= [%s]\n", hio_fd(io), + SOCKADDR_STR(hio_localaddr(io), localaddrstr), + SOCKADDR_STR(hio_peeraddr(io), peeraddrstr)); + */ + + EventLoop* loop = currentThreadEventLoop; + if (loop->connectionNum >= server->worker_connections) { + hlogw("over worker_connections"); + hio_close(io); + return; + } + ++loop->connectionNum; + + hio_setcb_close(io, on_close); + hio_setcb_read(io, on_recv); + hio_read(io); + if (service->keepalive_timeout > 0) { + hio_set_keepalive_timeout(io, service->keepalive_timeout); + } + + // new HttpHandler, delete on_close + HttpHandler* handler = new HttpHandler(io); + // ssl + handler->ssl = hio_is_ssl(io); + // ip:port + sockaddr_u* peeraddr = (sockaddr_u*)hio_peeraddr(io); + sockaddr_ip(peeraddr, handler->ip, sizeof(handler->ip)); + handler->port = sockaddr_port(peeraddr); + // http service + handler->service = service; + // websocket service + handler->ws_service = server->ws; + // FileCache + HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; + handler->files = &privdata->filecache; + hevent_set_userdata(io, handler); +} + +static void loop_thread(void* userdata) { + http_server_t* server = (http_server_t*)userdata; + HttpService* service = server->service; + + auto loop = std::make_shared(); + hloop_t* hloop = loop->loop(); + // http + if (server->listenfd[0] >= 0) { + hio_t* listenio = haccept(hloop, server->listenfd[0], on_accept); + hevent_set_userdata(listenio, server); + } + // https + if (server->listenfd[1] >= 0) { + hio_t* listenio = haccept(hloop, server->listenfd[1], on_accept); + hevent_set_userdata(listenio, server); + hio_enable_ssl(listenio); + if (server->ssl_ctx) { + hio_set_ssl_ctx(listenio, server->ssl_ctx); + } + } + + HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; + privdata->mutex_.lock(); + if (privdata->loops.size() == 0) { + // NOTE: fsync logfile when idle + hlog_disable_fsync(); + hidle_add(hloop, [](hidle_t*) { + hlog_fsync(); + }, INFINITE); + + // NOTE: add timer to update s_date every 1s + htimer_add(hloop, [](htimer_t* timer) { + gmtime_fmt(hloop_now(hevent_loop(timer)), HttpMessage::s_date); + }, 1000); + + // document_root + if (service->document_root.size() > 0 && service->GetStaticFilepath("/").empty()) { + service->Static("/", service->document_root.c_str()); + } + + // FileCache + FileCache* filecache = &privdata->filecache; + filecache->stat_interval = service->file_cache_stat_interval; + filecache->expired_time = service->file_cache_expired_time; + if (filecache->expired_time > 0) { + // NOTE: add timer to remove expired file cache + htimer_t* timer = htimer_add(hloop, [](htimer_t* timer) { + FileCache* filecache = (FileCache*)hevent_userdata(timer); + filecache->RemoveExpiredFileCache(); + }, filecache->expired_time * 1000); + hevent_set_userdata(timer, filecache); + } + } + privdata->loops.push_back(loop); + privdata->mutex_.unlock(); + + hlogi("EventLoop started, pid=%ld tid=%ld", hv_getpid(), hv_gettid()); + if (server->onWorkerStart) { + loop->queueInLoop([server](){ + server->onWorkerStart(); + }); + } + + loop->run(); + + if (server->onWorkerStop) { + server->onWorkerStop(); + } + hlogi("EventLoop stopped, pid=%ld tid=%ld", hv_getpid(), hv_gettid()); +} + +/* @workflow: + * http_server_run -> Listen -> master_workers_run / hthread_create -> + * loop_thread -> accept -> EventLoop::run -> + * on_accept -> new HttpHandler -> hio_read -> + * on_recv -> HttpHandler::FeedRecvData -> + * on_close -> delete HttpHandler + */ +int http_server_run(http_server_t* server, int wait) { + // http_port + if (server->port > 0) { + server->listenfd[0] = Listen(server->port, server->host); + if (server->listenfd[0] < 0) return server->listenfd[0]; + hlogi("http server listening on %s:%d", server->host, server->port); + } + // https_port + if (server->https_port > 0 && HV_WITH_SSL) { + server->listenfd[1] = Listen(server->https_port, server->host); + if (server->listenfd[1] < 0) return server->listenfd[1]; + hlogi("https server listening on %s:%d", server->host, server->https_port); + } + // SSL_CTX + if (server->listenfd[1] >= 0) { + if (server->ssl_ctx == NULL) { + server->ssl_ctx = hssl_ctx_instance(); + } + if (server->ssl_ctx == NULL) { + hloge("new SSL_CTX failed!"); + return ERR_NEW_SSL_CTX; + } +#ifdef WITH_NGHTTP2 +#ifdef WITH_OPENSSL + static unsigned char s_alpn_protos[] = "\x02h2\x08http/1.1\x08http/1.0\x08http/0.9"; + hssl_ctx_set_alpn_protos(server->ssl_ctx, s_alpn_protos, sizeof(s_alpn_protos) - 1); +#endif +#endif + } + + HttpServerPrivdata* privdata = new HttpServerPrivdata; + server->privdata = privdata; + if (server->service == NULL) { + privdata->service = std::make_shared(); + server->service = privdata->service.get(); + } + + if (server->worker_processes) { + // multi-processes + return master_workers_run(loop_thread, server, server->worker_processes, server->worker_threads, wait); + } + else { + // multi-threads + if (server->worker_threads == 0) server->worker_threads = 1; + for (int i = wait ? 1 : 0; i < server->worker_threads; ++i) { + hthread_t thrd = hthread_create((hthread_routine)loop_thread, server); + privdata->threads.push_back(thrd); + } + if (wait) { + loop_thread(server); + } + return 0; + } +} + +/* @workflow: + * http_server_stop -> EventLoop::stop -> hthread_join + */ +int http_server_stop(http_server_t* server) { + HttpServerPrivdata* privdata = (HttpServerPrivdata*)server->privdata; + if (privdata == NULL) return 0; + +#ifdef OS_UNIX + if (server->worker_processes) { + signal_handle("stop"); + return 0; + } +#endif + + // wait for all threads started and all loops running + while (1) { + hv_delay(1); + std::lock_guard locker(privdata->mutex_); + // wait for all loops created + if (privdata->loops.size() < server->worker_threads) { + continue; + } + // wait for all loops running + bool all_loops_running = true; + for (auto& loop : privdata->loops) { + if (loop->status() < hv::Status::kRunning) { + all_loops_running = false; + break; + } + } + if (all_loops_running) break; + } + + // stop all loops + for (auto& loop : privdata->loops) { + loop->stop(); + } + + // join all threads + for (auto& thrd : privdata->threads) { + hthread_join(thrd); + } + + if (server->alloced_ssl_ctx && server->ssl_ctx) { + hssl_ctx_free(server->ssl_ctx); + server->alloced_ssl_ctx = 0; + server->ssl_ctx = NULL; + } + + delete privdata; + server->privdata = NULL; + return 0; +} diff --git a/external/libhv/libhv-1.3.2/http/server/HttpServer.h b/external/libhv/libhv-1.3.2/http/server/HttpServer.h new file mode 100644 index 0000000..115a5b6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpServer.h @@ -0,0 +1,148 @@ +#ifndef HV_HTTP_SERVER_H_ +#define HV_HTTP_SERVER_H_ + +#include "hexport.h" +#include "hssl.h" +#include "HttpService.h" +// #include "WebSocketServer.h" +namespace hv { +struct WebSocketService; +} +using hv::HttpService; +using hv::WebSocketService; + +typedef struct http_server_s { + char host[64]; + int port; // http_port + int https_port; + int http_version; + int worker_processes; + int worker_threads; + uint32_t worker_connections; // max_connections = workers * worker_connections + HttpService* service; // http service + WebSocketService* ws; // websocket service + void* userdata; + int listenfd[2]; // 0: http, 1: https + void* privdata; + // hooks + std::function onWorkerStart; + std::function onWorkerStop; + // SSL/TLS + hssl_ctx_t ssl_ctx; + unsigned alloced_ssl_ctx: 1; + +#ifdef __cplusplus + http_server_s() { + strcpy(host, "0.0.0.0"); + // port = DEFAULT_HTTP_PORT; + // https_port = DEFAULT_HTTPS_PORT; + // port = 8080; + // https_port = 8443; + port = https_port = 0; + http_version = 1; + worker_processes = 0; + worker_threads = 0; + worker_connections = 1024; + service = NULL; + ws = NULL; + listenfd[0] = listenfd[1] = -1; + userdata = NULL; + privdata = NULL; + // SSL/TLS + ssl_ctx = NULL; + alloced_ssl_ctx = 0; + } +#endif +} http_server_t; + +// @param wait: Whether to occupy current thread +HV_EXPORT int http_server_run(http_server_t* server, int wait = 1); + +// NOTE: stop all loops and join all threads +HV_EXPORT int http_server_stop(http_server_t* server); + +/* +#include "HttpServer.h" +using namespace hv; + +int main() { + HttpService service; + service.GET("/ping", [](HttpRequest* req, HttpResponse* resp) { + resp->body = "pong"; + return 200; + }); + + HttpServer server; + server.registerHttpService(&service); + server.setPort(8080); + server.setThreadNum(4); + server.run(); + return 0; +} +*/ + +namespace hv { + +class HttpServer : public http_server_t { +public: + HttpServer(HttpService* service = NULL) + : http_server_t() + { + this->service = service; + } + ~HttpServer() { stop(); } + + void registerHttpService(HttpService* service) { + this->service = service; + } + + void setHost(const char* host = "0.0.0.0") { + if (host) strcpy(this->host, host); + } + + void setPort(int port = 0, int ssl_port = 0) { + if (port >= 0) this->port = port; + if (ssl_port >= 0) this->https_port = ssl_port; + } + void setListenFD(int fd = -1, int ssl_fd = -1) { + if (fd >= 0) this->listenfd[0] = fd; + if (ssl_fd >= 0) this->listenfd[1] = ssl_fd; + } + + void setProcessNum(int num) { + this->worker_processes = num; + } + + void setThreadNum(int num) { + this->worker_threads = num; + } + + // SSL/TLS + int setSslCtx(hssl_ctx_t ssl_ctx) { + this->ssl_ctx = ssl_ctx; + return 0; + } + int newSslCtx(hssl_ctx_opt_t* opt) { + // NOTE: hssl_ctx_free in http_server_stop + hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); + if (ssl_ctx == NULL) return -1; + this->alloced_ssl_ctx = 1; + return setSslCtx(ssl_ctx); + } + + int run(bool wait = true) { + return http_server_run(this, wait); + } + + int start() { + return run(false); + } + + int stop() { + return http_server_stop(this); + } +}; + +} + +#endif // HV_HTTP_SERVER_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/HttpService.cpp b/external/libhv/libhv-1.3.2/http/server/HttpService.cpp new file mode 100644 index 0000000..acab0fa --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpService.cpp @@ -0,0 +1,209 @@ +#include "HttpService.h" +#include "HttpMiddleware.h" + +#include "hbase.h" // import hv_strendswith + +namespace hv { + +void HttpService::AddRoute(const char* path, http_method method, const http_handler& handler) { + std::shared_ptr method_handlers = NULL; + auto iter = pathHandlers.find(path); + if (iter == pathHandlers.end()) { + // add path + method_handlers = std::make_shared(); + pathHandlers[path] = method_handlers; + } + else { + method_handlers = iter->second; + } + for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { + if (iter->method == method) { + // update + iter->handler = handler; + return; + } + } + // add + method_handlers->push_back(http_method_handler(method, handler)); +} + +int HttpService::GetRoute(const char* url, http_method method, http_handler** handler) { + // {base_url}/path?query + const char* s = url; + const char* b = base_url.c_str(); + while (*s && *b && *s == *b) {++s;++b;} + if (*b != '\0') { + return HTTP_STATUS_NOT_FOUND; + } + const char* e = s; + while (*e && *e != '?') ++e; + + std::string path = std::string(s, e); + auto iter = pathHandlers.find(path); + if (iter == pathHandlers.end()) { + if (handler) *handler = NULL; + return HTTP_STATUS_NOT_FOUND; + } + auto method_handlers = iter->second; + for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { + if (iter->method == method) { + if (handler) *handler = &iter->handler; + return 0; + } + } + if (handler) *handler = NULL; + return HTTP_STATUS_METHOD_NOT_ALLOWED; +} + +int HttpService::GetRoute(HttpRequest* req, http_handler** handler) { + // {base_url}/path?query + const char* s = req->path.c_str(); + const char* b = base_url.c_str(); + while (*s && *b && *s == *b) {++s;++b;} + if (*b != '\0') { + return HTTP_STATUS_NOT_FOUND; + } + const char* e = s; + while (*e && *e != '?') ++e; + + std::string path = std::string(s, e); + const char *kp, *ks, *vp, *vs; + bool match; + for (auto iter = pathHandlers.begin(); iter != pathHandlers.end(); ++iter) { + kp = iter->first.c_str(); + vp = path.c_str(); + match = false; + std::map params; + + while (*kp && *vp) { + if (kp[0] == '*') { + // wildcard * + match = hv_strendswith(vp, kp+1); + break; + } else if (*kp != *vp) { + match = false; + break; + } else if (kp[0] == '/' && (kp[1] == ':' || kp[1] == '{')) { + // RESTful /:field/ + // RESTful /{field}/ + kp += 2; + ks = kp; + while (*kp && *kp != '/') {++kp;} + vp += 1; + vs = vp; + while (*vp && *vp != '/') {++vp;} + int klen = kp - ks; + if (*(ks-1) == '{' && *(kp-1) == '}') { + --klen; + } + params[std::string(ks, klen)] = std::string(vs, vp-vs); + continue; + } else { + ++kp; + ++vp; + } + } + + match = match ? match : (*kp == '\0' && *vp == '\0'); + + if (match) { + auto method_handlers = iter->second; + for (auto iter = method_handlers->begin(); iter != method_handlers->end(); ++iter) { + if (iter->method == req->method) { + for (auto& param : params) { + // RESTful /:field/ => req->query_params[field] + req->query_params[param.first] = param.second; + } + if (handler) *handler = &iter->handler; + return 0; + } + } + + if (params.size() == 0) { + if (handler) *handler = NULL; + return HTTP_STATUS_METHOD_NOT_ALLOWED; + } + } + } + if (handler) *handler = NULL; + return HTTP_STATUS_NOT_FOUND; +} + +void HttpService::Static(const char* path, const char* dir) { + std::string strPath(path); + if (strPath.back() != '/') strPath += '/'; + std::string strDir(dir); + if (strDir.back() == '/') strDir.pop_back(); + staticDirs[strPath] = strDir; +} + +std::string HttpService::GetStaticFilepath(const char* path) { + std::string filepath; + for (auto iter = staticDirs.begin(); iter != staticDirs.end(); ++iter) { + if (hv_strstartswith(path, iter->first.c_str())) { + filepath = iter->second + (path + iter->first.length() - 1); + break; + } + } + + if (filepath.empty()) { + return filepath; + } + + if (filepath.back() == '/') { + filepath += home_page; + } + return filepath; +} + +void HttpService::Proxy(const char* path, const char* url) { + proxies[path] = url; +} + +std::string HttpService::GetProxyUrl(const char* path) { + std::string url; + for (auto iter = proxies.begin(); iter != proxies.end(); ++iter) { + if (hv_strstartswith(path, iter->first.c_str())) { + url = iter->second + (path + iter->first.length()); + break; + } + } + return url; +} + +void HttpService::AddTrustProxy(const char* host) { + trustProxies.emplace_back(host); +} + +void HttpService::AddNoProxy(const char* host) { + noProxies.emplace_back(host); +} + +bool HttpService::IsTrustProxy(const char* host) { + if (!host || *host == '\0') return false; + bool trust = true; + if (trustProxies.size() != 0) { + trust = false; + for (const auto& trust_proxy : trustProxies) { + if (hv_wildcard_match(host, trust_proxy.c_str())) { + trust = true; + break; + } + } + } + if (noProxies.size() != 0) { + for (const auto& no_proxy : noProxies) { + if (hv_wildcard_match(host, no_proxy.c_str())) { + trust = false; + break; + } + } + } + return trust; +} + +void HttpService::AllowCORS() { + Use(HttpMiddleware::CORS); +} + +} diff --git a/external/libhv/libhv-1.3.2/http/server/HttpService.h b/external/libhv/libhv-1.3.2/http/server/HttpService.h new file mode 100644 index 0000000..c98cf1c --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/HttpService.h @@ -0,0 +1,281 @@ +#ifndef HV_HTTP_SERVICE_H_ +#define HV_HTTP_SERVICE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include "hexport.h" +#include "HttpMessage.h" +#include "HttpResponseWriter.h" +#include "HttpContext.h" + +#define DEFAULT_BASE_URL "/api/v1" +#define DEFAULT_DOCUMENT_ROOT "/var/www/html" +#define DEFAULT_HOME_PAGE "index.html" +#define DEFAULT_ERROR_PAGE "error.html" +#define DEFAULT_INDEXOF_DIR "/downloads/" +#define DEFAULT_KEEPALIVE_TIMEOUT 75000 // ms + +// for FileCache +#define MAX_FILE_CACHE_SIZE (1 << 22) // 4M +#define DEFAULT_FILE_CACHE_STAT_INTERVAL 10 // s +#define DEFAULT_FILE_CACHE_EXPIRED_TIME 60 // s + +/* + * @param[in] req: parsed structured http request + * @param[out] resp: structured http response + * @return 0: handle next + * http_status_code: handle done + */ +#define HTTP_STATUS_NEXT 0 +#define HTTP_STATUS_UNFINISHED 0 +// NOTE: http_sync_handler run on IO thread +typedef std::function http_sync_handler; +// NOTE: http_async_handler run on hv::async threadpool +typedef std::function http_async_handler; +// NOTE: http_ctx_handler run on IO thread, you can easily post HttpContextPtr to your consumer thread for processing. +typedef std::function http_ctx_handler; +// NOTE: http_state_handler run on IO thread +typedef std::function http_state_handler; + +struct http_handler { + http_sync_handler sync_handler; + http_async_handler async_handler; + http_ctx_handler ctx_handler; + http_state_handler state_handler; + + http_handler() {} + http_handler(http_sync_handler fn) : sync_handler(std::move(fn)) {} + http_handler(http_async_handler fn) : async_handler(std::move(fn)) {} + http_handler(http_ctx_handler fn) : ctx_handler(std::move(fn)) {} + http_handler(http_state_handler fn) : state_handler(std::move(fn)) {} + http_handler(const http_handler& rhs) + : sync_handler(std::move(rhs.sync_handler)) + , async_handler(std::move(rhs.async_handler)) + , ctx_handler(std::move(rhs.ctx_handler)) + , state_handler(std::move(rhs.state_handler)) + {} + + const http_handler& operator=(http_sync_handler fn) { + sync_handler = std::move(fn); + return *this; + } + const http_handler& operator=(http_async_handler fn) { + async_handler = std::move(fn); + return *this; + } + const http_handler& operator=(http_ctx_handler fn) { + ctx_handler = std::move(fn); + return *this; + } + const http_handler& operator=(http_state_handler fn) { + state_handler = std::move(fn); + return *this; + } + + bool isNull() { + return sync_handler == NULL && + async_handler == NULL && + ctx_handler == NULL; + } + + operator bool() { + return !isNull(); + } +}; + +typedef std::vector http_handlers; + +struct http_method_handler { + http_method method; + http_handler handler; + + http_method_handler() {} + http_method_handler(http_method m, const http_handler& h) : method(m), handler(h) {} +}; + +// method => http_method_handler +typedef std::list http_method_handlers; +// path => http_method_handlers +typedef std::unordered_map> http_path_handlers; + +namespace hv { + +struct HV_EXPORT HttpService { + /* handler chain */ + // preprocessor -> middleware -> processor -> postprocessor + http_handler preprocessor; + http_handlers middleware; + // processor: pathHandlers -> staticHandler -> errorHandler + http_handler processor; + http_handler postprocessor; + + /* API handlers */ + std::string base_url; + http_path_handlers pathHandlers; + + /* Static file service */ + http_handler staticHandler; + http_handler largeFileHandler; + std::string document_root; + std::string home_page; + std::string error_page; + // nginx: location => root + std::map> staticDirs; + /* Indexof directory service */ + std::string index_of; + http_handler errorHandler; + + /* Proxy service */ + /* Reverse proxy service */ + // nginx: location => proxy_pass + std::map> proxies; + /* Forward proxy service */ + StringList trustProxies; + StringList noProxies; + int proxy_connect_timeout; + int proxy_read_timeout; + int proxy_write_timeout; + + // options + int keepalive_timeout; + int max_file_cache_size; // cache small file + int file_cache_stat_interval; // stat file is modified + int file_cache_expired_time; // remove expired file cache + /* + * @test limit_rate + * @build make examples + * @server bin/httpd -c etc/httpd.conf -s restart -d + * @client bin/wget http://127.0.0.1:8080/downloads/test.zip + */ + int limit_rate; // limit send rate, unit: KB/s + + unsigned enable_access_log :1; + unsigned enable_forward_proxy :1; + + HttpService() { + // base_url = DEFAULT_BASE_URL; + + document_root = DEFAULT_DOCUMENT_ROOT; + home_page = DEFAULT_HOME_PAGE; + // error_page = DEFAULT_ERROR_PAGE; + // index_of = DEFAULT_INDEXOF_DIR; + + proxy_connect_timeout = DEFAULT_CONNECT_TIMEOUT; + proxy_read_timeout = 0; + proxy_write_timeout = 0; + + keepalive_timeout = DEFAULT_KEEPALIVE_TIMEOUT; + max_file_cache_size = MAX_FILE_CACHE_SIZE; + file_cache_stat_interval = DEFAULT_FILE_CACHE_STAT_INTERVAL; + file_cache_expired_time = DEFAULT_FILE_CACHE_EXPIRED_TIME; + limit_rate = -1; // unlimited + + enable_access_log = 1; + enable_forward_proxy = 0; + } + + void AddRoute(const char* path, http_method method, const http_handler& handler); + // @retval 0 OK, else HTTP_STATUS_NOT_FOUND, HTTP_STATUS_METHOD_NOT_ALLOWED + int GetRoute(const char* url, http_method method, http_handler** handler); + // RESTful API /:field/ => req->query_params["field"] + int GetRoute(HttpRequest* req, http_handler** handler); + + // Static("/", "/var/www/html") + void Static(const char* path, const char* dir); + // @retval / => /var/www/html/index.html + std::string GetStaticFilepath(const char* path); + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS + void AllowCORS(); + + // proxy + // forward proxy + void EnableForwardProxy() { enable_forward_proxy = 1; } + void AddTrustProxy(const char* host); + void AddNoProxy(const char* host); + bool IsTrustProxy(const char* host); + // reverse proxy + // Proxy("/api/v1/", "http://www.httpbin.org/"); + void Proxy(const char* path, const char* url); + // @retval /api/v1/test => http://www.httpbin.org/test + std::string GetProxyUrl(const char* path); + + hv::StringList Paths() { + hv::StringList paths; + for (auto& pair : pathHandlers) { + paths.emplace_back(pair.first); + } + return paths; + } + + // Handler = [ http_sync_handler, http_ctx_handler ] + template + void Use(Handler handlerFunc) { + middleware.emplace_back(handlerFunc); + } + + // Inspired by github.com/gin-gonic/gin + // Handler = [ http_sync_handler, http_async_handler, http_ctx_handler, http_state_handler ] + template + void Handle(const char* httpMethod, const char* relativePath, Handler handlerFunc) { + AddRoute(relativePath, http_method_enum(httpMethod), http_handler(handlerFunc)); + } + + // HEAD + template + void HEAD(const char* relativePath, Handler handlerFunc) { + Handle("HEAD", relativePath, handlerFunc); + } + + // GET + template + void GET(const char* relativePath, Handler handlerFunc) { + Handle("GET", relativePath, handlerFunc); + } + + // POST + template + void POST(const char* relativePath, Handler handlerFunc) { + Handle("POST", relativePath, handlerFunc); + } + + // PUT + template + void PUT(const char* relativePath, Handler handlerFunc) { + Handle("PUT", relativePath, handlerFunc); + } + + // DELETE + // NOTE: Windows #define DELETE as a macro, we have to replace DELETE with Delete. + template + void Delete(const char* relativePath, Handler handlerFunc) { + Handle("DELETE", relativePath, handlerFunc); + } + + // PATCH + template + void PATCH(const char* relativePath, Handler handlerFunc) { + Handle("PATCH", relativePath, handlerFunc); + } + + // Any + template + void Any(const char* relativePath, Handler handlerFunc) { + Handle("HEAD", relativePath, handlerFunc); + Handle("GET", relativePath, handlerFunc); + Handle("POST", relativePath, handlerFunc); + Handle("PUT", relativePath, handlerFunc); + Handle("DELETE", relativePath, handlerFunc); + Handle("PATCH", relativePath, handlerFunc); + } +}; + +} + +#endif // HV_HTTP_SERVICE_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/WebSocketServer.h b/external/libhv/libhv-1.3.2/http/server/WebSocketServer.h new file mode 100644 index 0000000..6eee36e --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/WebSocketServer.h @@ -0,0 +1,46 @@ +#ifndef HV_WEBSOCKET_SERVER_H_ +#define HV_WEBSOCKET_SERVER_H_ + +/* + * @demo examples/websocket_server_test.cpp + */ + +#include "HttpServer.h" +#include "WebSocketChannel.h" + +#define websocket_server_t http_server_t +#define websocket_server_run http_server_run +#define websocket_server_stop http_server_stop + +namespace hv { + +struct WebSocketService { + std::function onopen; + std::function onmessage; + std::function onclose; + int ping_interval; + + WebSocketService() : ping_interval(0) {} + + void setPingInterval(int ms) { + ping_interval = ms; + } +}; + +class WebSocketServer : public HttpServer { +public: + WebSocketServer(WebSocketService* service = NULL) + : HttpServer() + { + this->ws = service; + } + ~WebSocketServer() { stop(); } + + void registerWebSocketService(WebSocketService* service) { + this->ws = service; + } +}; + +} + +#endif // HV_WEBSOCKET_SERVER_H_ diff --git a/external/libhv/libhv-1.3.2/http/server/http_page.cpp b/external/libhv/libhv-1.3.2/http/server/http_page.cpp new file mode 100644 index 0000000..47d6fb9 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/http_page.cpp @@ -0,0 +1,103 @@ +#include "http_page.h" +#include "hdir.h" + +#define AUTOINDEX_FILENAME_MAXLEN 50 + +void make_http_status_page(http_status status_code, std::string& page) { + char szCode[8]; + snprintf(szCode, sizeof(szCode), "%d ", status_code); + const char* status_message = http_status_str(status_code); + page += R"( + + + )"; + page += szCode; page += status_message; + page += R"( + + +

)"; + page += szCode; page += status_message; + page += R"(

+
+ +)"; +} + +void make_index_of_page(const char* dir, std::string& page, const char* url) { + char c_str[1024] = {0}; + snprintf(c_str, sizeof(c_str), R"( + + + Index of %s + + +

Index of %s

+
+)", url, url); + page += c_str; + + page += " \n"; + page += R"( + + + + +)"; + +#define _ADD_TD_(page, td) \ + page += " \n"; \ + + std::list dirs; + listdir(dir, dirs); + for (auto& item : dirs) { + if (item.name[0] == '.' && item.name[1] == '\0') continue; + page += " \n"; + size_t len = strlen(item.name) + (item.type == 'd'); + // name + snprintf(c_str, sizeof(c_str), "%s%s", + item.name, + item.type == 'd' ? "/" : "", + len < AUTOINDEX_FILENAME_MAXLEN ? item.name : std::string(item.name, item.name+AUTOINDEX_FILENAME_MAXLEN-4).append("...").c_str(), + item.type == 'd' ? "/" : ""); + _ADD_TD_(page, c_str) + if (strcmp(item.name, "..") != 0) { + // mtime + struct tm* tm = localtime(&item.mtime); + snprintf(c_str, sizeof(c_str), "%04d-%02d-%02d %02d:%02d:%02d", + tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); + _ADD_TD_(page, c_str) + // size + if (item.type == 'd') { + page += '-'; + } + else { + float hsize; + if (item.size < 1024) { + snprintf(c_str, sizeof(c_str), "%lu", (unsigned long)item.size); + } + else if ((hsize = item.size/1024.0f) < 1024.0f) { + snprintf(c_str, sizeof(c_str), "%.1fK", hsize); + } + else if ((hsize /= 1024.0f) < 1024.0f) { + snprintf(c_str, sizeof(c_str), "%.1fM", hsize); + } + else { + hsize /= 1024.0f; + snprintf(c_str, sizeof(c_str), "%.1fG", hsize); + } + _ADD_TD_(page, c_str) + } + } + page += " \n"; + } + +#undef _ADD_TD_ + + page += R"(
NameDateSize
"; \ + page += td; \ + page += "
+
+ + +)"; +} diff --git a/external/libhv/libhv-1.3.2/http/server/http_page.h b/external/libhv/libhv-1.3.2/http/server/http_page.h new file mode 100644 index 0000000..4cd8179 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/server/http_page.h @@ -0,0 +1,56 @@ +#ifndef HV_HTTP_PAGE_H_ +#define HV_HTTP_PAGE_H_ + +#include + +#include "httpdef.h" + +/* + + + + 404 Not Found + + +

404 Not Found

+
+ + + */ +void make_http_status_page(http_status status_code, std::string& page); + +/* + + + + Index of /downloads/ + + +

Index of /downloads/

+
+ + + + + + + + + + + + + + + + + + +
NameDateSize
../
libhv-vs-nginx.png2021-03-10 12:33:57211.4K
中文.html2022-04-25 15:37:12191
+
+ + + */ +void make_index_of_page(const char* dir, std::string& page, const char* url = ""); + +#endif // HV_HTTP_PAGE_H_ diff --git a/external/libhv/libhv-1.3.2/http/websocket_parser.c b/external/libhv/libhv-1.3.2/http/websocket_parser.c new file mode 100644 index 0000000..96baf20 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/websocket_parser.c @@ -0,0 +1,249 @@ +#include "websocket_parser.h" +#include +#include + +#ifdef assert +# define assertFalse(msg) assert(0 && msg) +#else +# define assertFalse(msg) +#endif + +#define SET_STATE(V) parser->state = V +#define HAS_DATA() (p < end ) +#define CC (*p) +#define GET_NPARSED() ( (p == end) ? len : (p - data) ) + +#define NOTIFY_CB(FOR) \ +do { \ + if (settings->on_##FOR) { \ + if (settings->on_##FOR(parser) != 0) { \ + return GET_NPARSED(); \ + } \ + } \ +} while (0) + +#define EMIT_DATA_CB(FOR, ptr, len) \ +do { \ + if (settings->on_##FOR) { \ + if (settings->on_##FOR(parser, ptr, len) != 0) { \ + return GET_NPARSED(); \ + } \ + } \ +} while (0) + +enum state { + s_start, + s_head, + s_length, + s_mask, + s_body, +}; + +void websocket_parser_init(websocket_parser * parser) { + void *data = parser->data; /* preserve application data */ + memset(parser, 0, sizeof(*parser)); + parser->data = data; + parser->state = s_start; +} + +void websocket_parser_settings_init(websocket_parser_settings *settings) { + memset(settings, 0, sizeof(*settings)); +} + +size_t websocket_parser_execute(websocket_parser *parser, const websocket_parser_settings *settings, const char *data, size_t len) { + const char * p; + const char * end = data + len; + size_t frame_offset = 0; + + for(p = data; p != end; p++) { + switch(parser->state) { + case s_start: + parser->offset = 0; + parser->length = 0; + parser->mask_offset = 0; + parser->flags = (websocket_flags) (CC & WS_OP_MASK); + if(CC & (1<<7)) { + parser->flags |= WS_FIN; + } + SET_STATE(s_head); + + frame_offset++; + break; + case s_head: + parser->length = (size_t)CC & 0x7F; + if(CC & 0x80) { + parser->flags |= WS_HAS_MASK; + } + if(parser->length >= 126) { + if(parser->length == 127) { + parser->require = 8; + } else { + parser->require = 2; + } + parser->length = 0; + SET_STATE(s_length); + } else if (parser->flags & WS_HAS_MASK) { + SET_STATE(s_mask); + parser->require = 4; + } else if (parser->length) { + SET_STATE(s_body); + parser->require = parser->length; + NOTIFY_CB(frame_header); + } else { + SET_STATE(s_start); + NOTIFY_CB(frame_header); + NOTIFY_CB(frame_end); + } + + frame_offset++; + break; + case s_length: + while(HAS_DATA() && parser->require) { + parser->length <<= 8; + parser->length |= (unsigned char)CC; + parser->require--; + frame_offset++; + p++; + } + p--; + if(!parser->require) { + if (parser->flags & WS_HAS_MASK) { + SET_STATE(s_mask); + parser->require = 4; + } else if (parser->length) { + SET_STATE(s_body); + parser->require = parser->length; + NOTIFY_CB(frame_header); + } else { + SET_STATE(s_start); + NOTIFY_CB(frame_header); + NOTIFY_CB(frame_end); + } + } + break; + case s_mask: + while(HAS_DATA() && parser->require) { + parser->mask[4 - parser->require--] = CC; + frame_offset++; + p++; + } + p--; + if(!parser->require) { + if(parser->length) { + SET_STATE(s_body); + parser->require = parser->length; + NOTIFY_CB(frame_header); + } else { + SET_STATE(s_start); + NOTIFY_CB(frame_header); + NOTIFY_CB(frame_end); + } + } + break; + case s_body: + if(parser->require) { + if(p + parser->require <= end) { + EMIT_DATA_CB(frame_body, p, parser->require); + p += parser->require; + parser->require = 0; + frame_offset = p - data; + } else { + EMIT_DATA_CB(frame_body, p, end - p); + parser->require -= end - p; + p = end; + parser->offset += p - data - frame_offset; + frame_offset = 0; + } + + p--; + } + if(!parser->require) { + SET_STATE(s_start); + NOTIFY_CB(frame_end); + } + break; + default: + assertFalse("Unreachable case"); + } + } + + return GET_NPARSED(); +} + +void websocket_parser_decode(char * dst, const char * src, size_t len, websocket_parser * parser) { + size_t i = 0; + for(; i < len; i++) { + dst[i] = src[i] ^ parser->mask[(i + parser->mask_offset) % 4]; + } + + parser->mask_offset = (uint8_t) ((i + parser->mask_offset) % 4); +} + +uint8_t websocket_decode(char * dst, const char * src, size_t len, const char mask[4], uint8_t mask_offset) { + size_t i = 0; + for(; i < len; i++) { + dst[i] = src[i] ^ mask[(i + mask_offset) % 4]; + } + + return (uint8_t) ((i + mask_offset) % 4); +} + +size_t websocket_calc_frame_size(websocket_flags flags, size_t data_len) { + size_t size = data_len + 2; // body + 2 bytes of head + if(data_len >= 126) { + if(data_len > 0xFFFF) { + size += 8; + } else { + size += 2; + } + } + if(flags & WS_HAS_MASK) { + size += 4; + } + + return size; +} + +size_t websocket_build_frame(char * frame, websocket_flags flags, const char mask[4], const char * data, size_t data_len) { + size_t body_offset = 0; + frame[0] = 0; + frame[1] = 0; + if(flags & WS_FIN) { + frame[0] = (char) (1 << 7); + } + frame[0] |= flags & WS_OP_MASK; + if(flags & WS_HAS_MASK) { + frame[1] = (char) (1 << 7); + } + if(data_len < 126) { + frame[1] |= data_len; + body_offset = 2; + } else if(data_len <= 0xFFFF) { + frame[1] |= 126; + frame[2] = (char) (data_len >> 8); + frame[3] = (char) (data_len & 0xFF); + body_offset = 4; + } else { + frame[1] |= 127; + frame[2] = (char) ((data_len >> 56) & 0xFF); + frame[3] = (char) ((data_len >> 48) & 0xFF); + frame[4] = (char) ((data_len >> 40) & 0xFF); + frame[5] = (char) ((data_len >> 32) & 0xFF); + frame[6] = (char) ((data_len >> 24) & 0xFF); + frame[7] = (char) ((data_len >> 16) & 0xFF); + frame[8] = (char) ((data_len >> 8) & 0xFF); + frame[9] = (char) ((data_len) & 0xFF); + body_offset = 10; + } + if(flags & WS_HAS_MASK) { + if(mask != NULL) { + memcpy(&frame[body_offset], mask, 4); + } + websocket_decode(&frame[body_offset + 4], data, data_len, &frame[body_offset], 0); + body_offset += 4; + } else { + memcpy(&frame[body_offset], data, data_len); + } + + return body_offset + data_len; +} diff --git a/external/libhv/libhv-1.3.2/http/websocket_parser.h b/external/libhv/libhv-1.3.2/http/websocket_parser.h new file mode 100644 index 0000000..e022125 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/websocket_parser.h @@ -0,0 +1,99 @@ +#ifndef WEBSOCKET_PARSER_H +#define WEBSOCKET_PARSER_H +#ifdef __cplusplus +extern "C" { +#endif + + +#include +#if defined(_WIN32) && !defined(__MINGW32__) && \ + (!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__) +#include +#include +typedef __int8 int8_t; +typedef unsigned __int8 uint8_t; +typedef __int16 int16_t; +typedef unsigned __int16 uint16_t; +typedef __int32 int32_t; +typedef unsigned __int32 uint32_t; +typedef __int64 int64_t; +typedef unsigned __int64 uint64_t; +#else +#include +#endif + +#define WEBSOCKET_UUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + +typedef struct websocket_parser websocket_parser; +typedef struct websocket_parser_settings websocket_parser_settings; + +typedef enum websocket_flags { + // opcodes + WS_OP_CONTINUE = 0x0, + WS_OP_TEXT = 0x1, + WS_OP_BINARY = 0x2, + WS_OP_CLOSE = 0x8, + WS_OP_PING = 0x9, + WS_OP_PONG = 0xA, + + // marks + WS_FINAL_FRAME = 0x10, + WS_HAS_MASK = 0x20, +} websocket_flags; + +#define WS_OP_MASK 0xF +#define WS_FIN WS_FINAL_FRAME + +typedef int (*websocket_data_cb) (websocket_parser*, const char * at, size_t length); +typedef int (*websocket_cb) (websocket_parser*); + +struct websocket_parser { + uint32_t state; + websocket_flags flags; + + char mask[4]; + uint8_t mask_offset; + + size_t length; + size_t require; + size_t offset; + + void * data; +}; + +struct websocket_parser_settings { + websocket_cb on_frame_header; + websocket_data_cb on_frame_body; + websocket_cb on_frame_end; +}; + +void websocket_parser_init(websocket_parser *parser); +void websocket_parser_settings_init(websocket_parser_settings *settings); +size_t websocket_parser_execute( + websocket_parser * parser, + const websocket_parser_settings *settings, + const char * data, + size_t len +); + +// Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and store mask's offset +void websocket_parser_decode(char * dst, const char * src, size_t len, websocket_parser * parser); + +// Apply XOR mask (see https://tools.ietf.org/html/rfc6455#section-5.3) and return mask's offset +uint8_t websocket_decode(char * dst, const char * src, size_t len, const char mask[4], uint8_t mask_offset); +#define websocket_encode(dst, src, len, mask, mask_offset) websocket_decode(dst, src, len, mask, mask_offset) + +// Calculate frame size using flags and data length +size_t websocket_calc_frame_size(websocket_flags flags, size_t data_len); + +// Create string representation of frame +size_t websocket_build_frame(char * frame, websocket_flags flags, const char mask[4], const char * data, size_t data_len); + +#define websocket_parser_get_opcode(p) (p->flags & WS_OP_MASK) +#define websocket_parser_has_mask(p) (p->flags & WS_HAS_MASK) +#define websocket_parser_has_final(p) (p->flags & WS_FIN) + +#ifdef __cplusplus +} +#endif +#endif //WEBSOCKET_PARSER_H diff --git a/external/libhv/libhv-1.3.2/http/wsdef.c b/external/libhv/libhv-1.3.2/http/wsdef.c new file mode 100644 index 0000000..a99d15a --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/wsdef.c @@ -0,0 +1,46 @@ +#include "wsdef.h" + +#include + +#include "sha1.h" +#include "base64.h" + +#include "websocket_parser.h" + +// base64_encode( SHA1(key + magic) ) +void ws_encode_key(const char* key, char accept[]) { + char magic[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; + unsigned char digest[20] = {0}; + HV_SHA1_CTX ctx; + HV_SHA1Init(&ctx); + HV_SHA1Update(&ctx, (unsigned char*)key, (uint32_t)strlen(key)); + HV_SHA1Update(&ctx, (unsigned char*)magic, (uint32_t)strlen(magic)); + HV_SHA1Final(digest, &ctx); + hv_base64_encode(digest, 20, accept); +} + +// fix-header[2] + var-length[2/8] + mask[4] + data[data_len] +int ws_calc_frame_size(int data_len, bool has_mask) { + int size = data_len + 2; + if (data_len >=126) { + if (data_len > 0xFFFF) { + size += 8; + } else { + size += 2; + } + } + if (has_mask) size += 4; + return size; +} + +int ws_build_frame( + char* out, + const char* data, int data_len, + const char mask[4], bool has_mask, + enum ws_opcode opcode, + bool fin) { + int flags = opcode; + if (fin) flags |= WS_FIN; + if (has_mask) flags |= WS_HAS_MASK; + return (int)websocket_build_frame(out, (websocket_flags)flags, mask, data, data_len); +} diff --git a/external/libhv/libhv-1.3.2/http/wsdef.h b/external/libhv/libhv-1.3.2/http/wsdef.h new file mode 100644 index 0000000..bbd0456 --- /dev/null +++ b/external/libhv/libhv-1.3.2/http/wsdef.h @@ -0,0 +1,89 @@ +#ifndef HV_WS_DEF_H_ +#define HV_WS_DEF_H_ + +#include "hexport.h" + +#include +#include // import rand + +#define SEC_WEBSOCKET_VERSION "Sec-WebSocket-Version" +#define SEC_WEBSOCKET_KEY "Sec-WebSocket-Key" +#define SEC_WEBSOCKET_ACCEPT "Sec-WebSocket-Accept" +#define SEC_WEBSOCKET_PROTOCOL "Sec-WebSocket-Protocol" +#define SEC_WEBSOCKET_EXTENSIONS "Sec-WebSocket-Extensions" + +#define WS_SERVER_MIN_FRAME_SIZE 2 +// 1000 1001 0000 0000 +#define WS_SERVER_PING_FRAME "\211\0" +// 1000 1010 0000 0000 +#define WS_SERVER_PONG_FRAME "\212\0" + +#define WS_CLIENT_MIN_FRAME_SIZE 6 +// 1000 1001 1000 0000 +#define WS_CLIENT_PING_FRAME "\211\200WSWS" +// 1000 1010 1000 0000 +#define WS_CLIENT_PONG_FRAME "\212\200WSWS" + +enum ws_session_type { + WS_CLIENT, + WS_SERVER, +}; + +enum ws_opcode { + WS_OPCODE_CONTINUE = 0x0, + WS_OPCODE_TEXT = 0x1, + WS_OPCODE_BINARY = 0x2, + WS_OPCODE_CLOSE = 0x8, + WS_OPCODE_PING = 0x9, + WS_OPCODE_PONG = 0xA, +}; + +BEGIN_EXTERN_C + +// Sec-WebSocket-Key => Sec-WebSocket-Accept +HV_EXPORT void ws_encode_key(const char* key, char accept[]); + +// fix-header[2] + var-length[2/8] + mask[4] + data[data_len] +HV_EXPORT int ws_calc_frame_size(int data_len, bool has_mask DEFAULT(false)); + +HV_EXPORT int ws_build_frame( + char* out, + const char* data, + int data_len, + const char mask[4], + bool has_mask DEFAULT(false), + enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), + bool fin DEFAULT(true)); + +HV_INLINE int ws_client_build_frame( + char* out, + const char* data, + int data_len, + /* const char mask[4] */ + /* bool has_mask = true */ + enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), + bool fin DEFAULT(true)) { + char mask[4] = {0}; + int i = 0; + int imask = rand(); + for (i = 0; i < 4; i++) { + mask[i] = (imask >> (8 * i)) & 0xff; + } + return ws_build_frame(out, data, data_len, mask, true, opcode, fin); +} + +HV_INLINE int ws_server_build_frame( + char* out, + const char* data, + int data_len, + /* const char mask[4] */ + /* bool has_mask = false */ + enum ws_opcode opcode DEFAULT(WS_OPCODE_TEXT), + bool fin DEFAULT(true)) { + char mask[4] = {0}; + return ws_build_frame(out, data, data_len, mask, false, opcode, fin); +} + +END_EXTERN_C + +#endif // HV_WS_DEF_H_ diff --git a/external/libhv/libhv-1.3.2/hv.h b/external/libhv/libhv-1.3.2/hv.h new file mode 100644 index 0000000..ef6fb2b --- /dev/null +++ b/external/libhv/libhv-1.3.2/hv.h @@ -0,0 +1,41 @@ +#ifndef HV_H_ +#define HV_H_ + +/** + * @copyright 2018 HeWei, all rights reserved. + */ + +// platform +#include "hconfig.h" +#include "hexport.h" +#include "hplatform.h" + +// c +#include "hdef.h" // +#include "hatomic.h"// +#include "herr.h" // +#include "htime.h" // +#include "hmath.h" // + +#include "hbase.h" +#include "hversion.h" +#include "hsysinfo.h" +#include "hproc.h" +#include "hthread.h" +#include "hmutex.h" +#include "hsocket.h" + +#include "hlog.h" +#include "hbuf.h" + +// cpp +#ifdef __cplusplus +#include "hmap.h" // +#include "hstring.h" // +#include "hfile.h" +#include "hpath.h" +#include "hdir.h" +#include "hurl.h" +#endif + +#endif // HV_H_ diff --git a/external/libhv/libhv-1.3.2/misc/grpc_server.h b/external/libhv/libhv-1.3.2/misc/grpc_server.h new file mode 100644 index 0000000..049d00b --- /dev/null +++ b/external/libhv/libhv-1.3.2/misc/grpc_server.h @@ -0,0 +1,45 @@ +#ifndef GRPC_SERVER_H +#define GRPC_SERVER_H + +#include "grpcpp/grpcpp.h" +using grpc::ServerBuilder; +using grpc::Server; +using grpc::Service; +using grpc::ServerCompletionQueue; + +// GRPC_DEFAULT_MAX_RECV_MESSAGE_LENGTH = 4M +// GRPC_DEFAULT_MAX_SEND_MESSAGE_LENGTH = 4M +#define GRPC_MAX_RECV_MESSAGE_LENGTH 1<<24 // 16M +#define GRPC_MAX_SEND_MESSAGE_LENGTH 1<<24 // 16M + +class GrpcServer { +public: + GrpcServer(int port) : _port(port) { + char srvaddr[128] = {0}; + snprintf(srvaddr, sizeof(srvaddr), "%s:%d", "0.0.0.0", _port); + build_.AddListeningPort(srvaddr, grpc::InsecureServerCredentials()); + build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIME_MS, 30000); + build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, 5000); + build_.AddChannelArgument(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1); + build_.SetMaxReceiveMessageSize(GRPC_MAX_RECV_MESSAGE_LENGTH); + build_.SetMaxSendMessageSize(GRPC_MAX_SEND_MESSAGE_LENGTH); + } + + void RegisterService(Service* service) { + build_.RegisterService(service); + } + + void Run(bool wait=true) { + server_ = build_.BuildAndStart(); + if (wait) { + server_->Wait(); + } + } + +public: + int _port; + ServerBuilder build_; + std::unique_ptr server_; +}; + +#endif // GRPC_SERVER_H diff --git a/external/libhv/libhv-1.3.2/misc/win32_getopt.h b/external/libhv/libhv-1.3.2/misc/win32_getopt.h new file mode 100644 index 0000000..d7e2601 --- /dev/null +++ b/external/libhv/libhv-1.3.2/misc/win32_getopt.h @@ -0,0 +1,653 @@ +#ifndef __GETOPT_H__ +/** + * DISCLAIMER + * This file is part of the mingw-w64 runtime package. + * + * The mingw-w64 runtime package and its code is distributed in the hope that it + * will be useful but WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESSED OR + * IMPLIED ARE HEREBY DISCLAIMED. This includes but is not limited to + * warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + /* + * Copyright (c) 2002 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Dieter Baron and Thomas Klausner. + * + * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. + */ + +#pragma warning(disable:4996) + +#define __GETOPT_H__ + +/* All the headers include this file. */ +#include +#include +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define REPLACE_GETOPT /* use this getopt as the system getopt(3) */ + +#ifdef REPLACE_GETOPT +int opterr = 1; /* if error message should be printed */ +int optind = 1; /* index into parent argv vector */ +int optopt = '?'; /* character checked for validity */ +#undef optreset /* see getopt.h */ +#define optreset __mingw_optreset +int optreset; /* reset getopt */ +char *optarg; /* argument associated with option */ +#endif + +//extern int optind; /* index of first non-option in argv */ +//extern int optopt; /* single option character, as parsed */ +//extern int opterr; /* flag to enable built-in diagnostics... */ +// /* (user may set to zero, to suppress) */ +// +//extern char *optarg; /* pointer to argument of current option */ + +#define PRINT_ERROR ((opterr) && (*options != ':')) + +#define FLAG_PERMUTE 0x01 /* permute non-options to the end of argv */ +#define FLAG_ALLARGS 0x02 /* treat non-options as args to option "-1" */ +#define FLAG_LONGONLY 0x04 /* operate as getopt_long_only */ + +/* return values */ +#define BADCH (int)'?' +#define BADARG ((*options == ':') ? (int)':' : (int)'?') +#define INORDER (int)1 + +#ifndef __CYGWIN__ +#define __progname __argv[0] +#else +extern char __declspec(dllimport) *__progname; +#endif + +#ifdef __CYGWIN__ +static char EMSG[] = ""; +#else +#define EMSG (char*)"" +#endif + +static int getopt_internal(int, char * const *, const char *, + const struct option *, int *, int); +static int parse_long_options(char * const *, const char *, + const struct option *, int *, int); +static int gcd(int, int); +static void permute_args(int, int, int, char * const *); + +static char *place = EMSG; /* option letter processing */ + +/* XXX: set optreset to 1 rather than these two */ +static int nonopt_start = -1; /* first non option argument (for permute) */ +static int nonopt_end = -1; /* first option after non options (for permute) */ + +/* Error messages */ +static const char recargchar[] = "option requires an argument -- %c"; +static const char recargstring[] = "option requires an argument -- %s"; +static const char ambig[] = "ambiguous option -- %.*s"; +static const char noarg[] = "option doesn't take an argument -- %.*s"; +static const char illoptchar[] = "unknown option -- %c"; +static const char illoptstring[] = "unknown option -- %s"; + +static void +_vwarnx(const char *fmt,va_list ap) +{ + (void)fprintf(stderr,"%s: ",__progname); + if (fmt != NULL) + (void)vfprintf(stderr,fmt,ap); + (void)fprintf(stderr,"\n"); +} + +static void +warnx(const char *fmt,...) +{ + va_list ap; + va_start(ap,fmt); + _vwarnx(fmt,ap); + va_end(ap); +} + +/* + * Compute the greatest common divisor of a and b. + */ +static int +gcd(int a, int b) +{ + int c; + + c = a % b; + while (c != 0) { + a = b; + b = c; + c = a % b; + } + + return (b); +} + +/* + * Exchange the block from nonopt_start to nonopt_end with the block + * from nonopt_end to opt_end (keeping the same order of arguments + * in each block). + */ +static void +permute_args(int panonopt_start, int panonopt_end, int opt_end, + char * const *nargv) +{ + int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos; + char *swap; + + /* + * compute lengths of blocks and number and size of cycles + */ + nnonopts = panonopt_end - panonopt_start; + nopts = opt_end - panonopt_end; + ncycle = gcd(nnonopts, nopts); + cyclelen = (opt_end - panonopt_start) / ncycle; + + for (i = 0; i < ncycle; i++) { + cstart = panonopt_end+i; + pos = cstart; + for (j = 0; j < cyclelen; j++) { + if (pos >= panonopt_end) + pos -= nnonopts; + else + pos += nopts; + swap = nargv[pos]; + /* LINTED const cast */ + ((char **) nargv)[pos] = nargv[cstart]; + /* LINTED const cast */ + ((char **)nargv)[cstart] = swap; + } + } +} + +#ifdef REPLACE_GETOPT +/* + * getopt -- + * Parse argc/argv argument vector. + * + * [eventually this will replace the BSD getopt] + */ +int +getopt(int nargc, char * const *nargv, const char *options) +{ + + /* + * We don't pass FLAG_PERMUTE to getopt_internal() since + * the BSD getopt(3) (unlike GNU) has never done this. + * + * Furthermore, since many privileged programs call getopt() + * before dropping privileges it makes sense to keep things + * as simple (and bug-free) as possible. + */ + return (getopt_internal(nargc, nargv, options, NULL, NULL, 0)); +} +#endif /* REPLACE_GETOPT */ + +//extern int getopt(int nargc, char * const *nargv, const char *options); + +#ifdef _BSD_SOURCE +/* + * BSD adds the non-standard `optreset' feature, for reinitialisation + * of `getopt' parsing. We support this feature, for applications which + * proclaim their BSD heritage, before including this header; however, + * to maintain portability, developers are advised to avoid it. + */ +# define optreset __mingw_optreset +extern int optreset; +#endif +#ifdef __cplusplus +} +#endif +/* + * POSIX requires the `getopt' API to be specified in `unistd.h'; + * thus, `unistd.h' includes this header. However, we do not want + * to expose the `getopt_long' or `getopt_long_only' APIs, when + * included in this manner. Thus, close the standard __GETOPT_H__ + * declarations block, and open an additional __GETOPT_LONG_H__ + * specific block, only when *not* __UNISTD_H_SOURCED__, in which + * to declare the extended API. + */ +#endif /* !defined(__GETOPT_H__) */ + +#if !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) +#define __GETOPT_LONG_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +struct option /* specification for a long form option... */ +{ + const char *name; /* option name, without leading hyphens */ + int has_arg; /* does it take an argument? */ + int *flag; /* where to save its status, or NULL */ + int val; /* its associated status value */ +}; + +enum /* permitted values for its `has_arg' field... */ +{ + no_argument = 0, /* option never takes an argument */ + required_argument, /* option always requires an argument */ + optional_argument /* option may take an argument */ +}; + +/* + * parse_long_options -- + * Parse long options in argc/argv argument vector. + * Returns -1 if short_too is set and the option does not match long_options. + */ +static int +parse_long_options(char * const *nargv, const char *options, + const struct option *long_options, int *idx, int short_too) +{ + char *current_argv, *has_equal; + size_t current_argv_len; + int i, ambiguous, match; + +#define IDENTICAL_INTERPRETATION(_x, _y) \ + (long_options[(_x)].has_arg == long_options[(_y)].has_arg && \ + long_options[(_x)].flag == long_options[(_y)].flag && \ + long_options[(_x)].val == long_options[(_y)].val) + + current_argv = place; + match = -1; + ambiguous = 0; + + optind++; + + if ((has_equal = strchr(current_argv, '=')) != NULL) { + /* argument found (--option=arg) */ + current_argv_len = has_equal - current_argv; + has_equal++; + } else + current_argv_len = strlen(current_argv); + + for (i = 0; long_options[i].name; i++) { + /* find matching long option */ + if (strncmp(current_argv, long_options[i].name, + current_argv_len)) + continue; + + if (strlen(long_options[i].name) == current_argv_len) { + /* exact match */ + match = i; + ambiguous = 0; + break; + } + /* + * If this is a known short option, don't allow + * a partial match of a single character. + */ + if (short_too && current_argv_len == 1) + continue; + + if (match == -1) /* partial match */ + match = i; + else if (!IDENTICAL_INTERPRETATION(i, match)) + ambiguous = 1; + } + if (ambiguous) { + /* ambiguous abbreviation */ + if (PRINT_ERROR) + warnx(ambig, (int)current_argv_len, + current_argv); + optopt = 0; + return (BADCH); + } + if (match != -1) { /* option found */ + if (long_options[match].has_arg == no_argument + && has_equal) { + if (PRINT_ERROR) + warnx(noarg, (int)current_argv_len, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + return (BADARG); + } + if (long_options[match].has_arg == required_argument || + long_options[match].has_arg == optional_argument) { + if (has_equal) + optarg = has_equal; + else if (long_options[match].has_arg == + required_argument) { + /* + * optional argument doesn't use next nargv + */ + optarg = nargv[optind++]; + } + } + if ((long_options[match].has_arg == required_argument) + && (optarg == NULL)) { + /* + * Missing argument; leading ':' indicates no error + * should be generated. + */ + if (PRINT_ERROR) + warnx(recargstring, + current_argv); + /* + * XXX: GNU sets optopt to val regardless of flag + */ + if (long_options[match].flag == NULL) + optopt = long_options[match].val; + else + optopt = 0; + --optind; + return (BADARG); + } + } else { /* unknown option */ + if (short_too) { + --optind; + return (-1); + } + if (PRINT_ERROR) + warnx(illoptstring, current_argv); + optopt = 0; + return (BADCH); + } + if (idx) + *idx = match; + if (long_options[match].flag) { + *long_options[match].flag = long_options[match].val; + return (0); + } else + return (long_options[match].val); +#undef IDENTICAL_INTERPRETATION +} + +/* + * getopt_internal -- + * Parse argc/argv argument vector. Called by user level routines. + */ +static int +getopt_internal(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx, int flags) +{ + char *oli; /* option letter list index */ + int optchar, short_too; + static int posixly_correct = -1; + + if (options == NULL) + return (-1); + + /* + * XXX Some GNU programs (like cvs) set optind to 0 instead of + * XXX using optreset. Work around this braindamage. + */ + if (optind == 0) + optind = optreset = 1; + + /* + * Disable GNU extensions if POSIXLY_CORRECT is set or options + * string begins with a '+'. + * + * CV, 2009-12-14: Check POSIXLY_CORRECT anew if optind == 0 or + * optreset != 0 for GNU compatibility. + */ + if (posixly_correct == -1 || optreset != 0) + posixly_correct = (getenv("POSIXLY_CORRECT") != NULL); + if (*options == '-') + flags |= FLAG_ALLARGS; + else if (posixly_correct || *options == '+') + flags &= ~FLAG_PERMUTE; + if (*options == '+' || *options == '-') + options++; + + optarg = NULL; + if (optreset) + nonopt_start = nonopt_end = -1; +start: + if (optreset || !*place) { /* update scanning pointer */ + optreset = 0; + if (optind >= nargc) { /* end of argument vector */ + place = EMSG; + if (nonopt_end != -1) { + /* do permutation, if we have to */ + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + else if (nonopt_start != -1) { + /* + * If we skipped non-options, set optind + * to the first of them. + */ + optind = nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + if (*(place = nargv[optind]) != '-' || + (place[1] == '\0' && strchr(options, '-') == NULL)) { + place = EMSG; /* found non-option */ + if (flags & FLAG_ALLARGS) { + /* + * GNU extension: + * return non-option as argument to option 1 + */ + optarg = nargv[optind++]; + return (INORDER); + } + if (!(flags & FLAG_PERMUTE)) { + /* + * If no permutation wanted, stop parsing + * at first non-option. + */ + return (-1); + } + /* do permutation */ + if (nonopt_start == -1) + nonopt_start = optind; + else if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + nonopt_start = optind - + (nonopt_end - nonopt_start); + nonopt_end = -1; + } + optind++; + /* process next argument */ + goto start; + } + if (nonopt_start != -1 && nonopt_end == -1) + nonopt_end = optind; + + /* + * If we have "-" do nothing, if "--" we are done. + */ + if (place[1] != '\0' && *++place == '-' && place[1] == '\0') { + optind++; + place = EMSG; + /* + * We found an option (--), so if we skipped + * non-options, we have to permute. + */ + if (nonopt_end != -1) { + permute_args(nonopt_start, nonopt_end, + optind, nargv); + optind -= nonopt_end - nonopt_start; + } + nonopt_start = nonopt_end = -1; + return (-1); + } + } + + /* + * Check long options if: + * 1) we were passed some + * 2) the arg is not just "-" + * 3) either the arg starts with -- we are getopt_long_only() + */ + if (long_options != NULL && place != nargv[optind] && + (*place == '-' || (flags & FLAG_LONGONLY))) { + short_too = 0; + if (*place == '-') + place++; /* --foo long option */ + else if (*place != ':' && strchr(options, *place) != NULL) + short_too = 1; /* could be short option too */ + + optchar = parse_long_options(nargv, options, long_options, + idx, short_too); + if (optchar != -1) { + place = EMSG; + return (optchar); + } + } + + if ((optchar = (int)*place++) == (int)':' || + (optchar == (int)'-' && *place != '\0') || + (oli = (char*)strchr(options, optchar)) == NULL) { + /* + * If the user specified "-" and '-' isn't listed in + * options, return -1 (non-option) as per POSIX. + * Otherwise, it is an unknown option character (or ':'). + */ + if (optchar == (int)'-' && *place == '\0') + return (-1); + if (!*place) + ++optind; + if (PRINT_ERROR) + warnx(illoptchar, optchar); + optopt = optchar; + return (BADCH); + } + if (long_options != NULL && optchar == 'W' && oli[1] == ';') { + /* -W long-option */ + if (*place) /* no space */ + /* NOTHING */; + else if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else /* white space */ + place = nargv[optind]; + optchar = parse_long_options(nargv, options, long_options, + idx, 0); + place = EMSG; + return (optchar); + } + if (*++oli != ':') { /* doesn't take argument */ + if (!*place) + ++optind; + } else { /* takes (optional) argument */ + optarg = NULL; + if (*place) /* no white space */ + optarg = place; + else if (oli[1] != ':') { /* arg not optional */ + if (++optind >= nargc) { /* no arg */ + place = EMSG; + if (PRINT_ERROR) + warnx(recargchar, optchar); + optopt = optchar; + return (BADARG); + } else + optarg = nargv[optind]; + } + place = EMSG; + ++optind; + } + /* dump back option letter */ + return (optchar); +} + +/* + * getopt_long -- + * Parse argc/argv argument vector. + */ +int +getopt_long(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE)); +} + +/* + * getopt_long_only -- + * Parse argc/argv argument vector. + */ +int +getopt_long_only(int nargc, char * const *nargv, const char *options, + const struct option *long_options, int *idx) +{ + + return (getopt_internal(nargc, nargv, options, long_options, idx, + FLAG_PERMUTE|FLAG_LONGONLY)); +} + +//extern int getopt_long(int nargc, char * const *nargv, const char *options, +// const struct option *long_options, int *idx); +//extern int getopt_long_only(int nargc, char * const *nargv, const char *options, +// const struct option *long_options, int *idx); +/* + * Previous MinGW implementation had... + */ +#ifndef HAVE_DECL_GETOPT +/* + * ...for the long form API only; keep this for compatibility. + */ +# define HAVE_DECL_GETOPT 1 +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* !defined(__UNISTD_H_SOURCED__) && !defined(__GETOPT_LONG_H__) */ diff --git a/external/libhv/libhv-1.3.2/mqtt/mqtt_client.c b/external/libhv/libhv-1.3.2/mqtt/mqtt_client.c new file mode 100644 index 0000000..2a62d38 --- /dev/null +++ b/external/libhv/libhv-1.3.2/mqtt/mqtt_client.c @@ -0,0 +1,602 @@ +#include "mqtt_client.h" +#include "hbase.h" +#include "hlog.h" +#include "herr.h" +#include "hendian.h" + +static unsigned short mqtt_next_mid() { + static unsigned short s_mid = 0; + return ++s_mid; +} + +static int mqtt_client_send(mqtt_client_t* cli, const void* buf, int len) { + // thread-safe + hmutex_lock(&cli->mutex_); + int nwrite = hio_write(cli->io, buf, len); + hmutex_unlock(&cli->mutex_); + return nwrite; +} + +static int mqtt_send_head(hio_t* io, int type, int length) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = type; + head.length = length; + unsigned char headbuf[8] = { 0 }; + int headlen = mqtt_head_pack(&head, headbuf); + return mqtt_client_send(cli, headbuf, headlen); +} + +static int mqtt_send_head_with_mid(hio_t* io, int type, unsigned short mid) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = type; + if (head.type == MQTT_TYPE_PUBREL) { + head.qos = 1; + } + head.length = 2; + unsigned char headbuf[8] = { 0 }; + unsigned char* p = headbuf; + int headlen = mqtt_head_pack(&head, p); + p += headlen; + PUSH16(p, mid); + return mqtt_client_send(cli, headbuf, headlen + 2); +} + +static void mqtt_send_ping(hio_t* io) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + if (cli->ping_cnt++ == 3) { + hloge("mqtt no pong!"); + hio_close(io); + return; + } + mqtt_send_head(io, MQTT_TYPE_PINGREQ, 0); +} + +static void mqtt_send_pong(hio_t* io) { + mqtt_send_head(io, MQTT_TYPE_PINGRESP, 0); +} + +static void mqtt_send_disconnect(hio_t* io) { + mqtt_send_head(io, MQTT_TYPE_DISCONNECT, 0); +} + +/* + * MQTT_TYPE_CONNECT + * 2 + protocol_name + 1 protocol_version + 1 conn_flags + 2 keepalive + 2 + [client_id] + + * [2 + will_topic + 2 + will_payload] + + * [2 + username] + [2 + password] + */ +static int mqtt_client_login(mqtt_client_t* cli) { + int len = 2 + 1 + 1 + 2 + 2; + unsigned short cid_len = 0, + will_topic_len = 0, + will_payload_len = 0, + username_len = 0, + password_len = 0; + unsigned char conn_flags = 0; + + // protocol_name_len + len += cli->protocol_version == MQTT_PROTOCOL_V31 ? 6 : 4; + if (*cli->client_id) { + cid_len = strlen(cli->client_id); + } else { + cid_len = 20; + hv_random_string(cli->client_id, cid_len); + hlogi("MQTT client_id: %.*s", (int)cid_len, cli->client_id); + } + len += cid_len; + if (cid_len == 0) cli->clean_session = 1; + if (cli->clean_session) { + conn_flags |= MQTT_CONN_CLEAN_SESSION; + } + if (cli->will && cli->will->topic && cli->will->payload) { + will_topic_len = cli->will->topic_len ? cli->will->topic_len : strlen(cli->will->topic); + will_payload_len = cli->will->payload_len ? cli->will->payload_len : strlen(cli->will->payload); + if (will_topic_len && will_payload_len) { + conn_flags |= MQTT_CONN_HAS_WILL; + conn_flags |= ((cli->will->qos & 3) << 3); + if (cli->will->retain) { + conn_flags |= MQTT_CONN_WILL_RETAIN; + } + len += 2 + will_topic_len; + len += 2 + will_payload_len; + } + } + if (*cli->username) { + username_len = strlen(cli->username); + if (username_len) { + conn_flags |= MQTT_CONN_HAS_USERNAME; + len += 2 + username_len; + } + } + if (*cli->password) { + password_len = strlen(cli->password); + if (password_len) { + conn_flags |= MQTT_CONN_HAS_PASSWORD; + len += 2 + password_len; + } + } + + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = MQTT_TYPE_CONNECT; + head.length = len; + int buflen = mqtt_estimate_length(&head); + unsigned char* buf = NULL; + HV_STACK_ALLOC(buf, buflen); + unsigned char* p = buf; + int headlen = mqtt_head_pack(&head, p); + p += headlen; + // TODO: Not implement MQTT_PROTOCOL_V5 + if (cli->protocol_version == MQTT_PROTOCOL_V31) { + PUSH16(p, 6); + PUSH_N(p, MQTT_PROTOCOL_NAME_v31, 6); + } else { + PUSH16(p, 4); + PUSH_N(p, MQTT_PROTOCOL_NAME, 4); + } + PUSH8(p, cli->protocol_version); + PUSH8(p, conn_flags); + PUSH16(p, cli->keepalive); + PUSH16(p, cid_len); + if (cid_len > 0) { + PUSH_N(p, cli->client_id, cid_len); + } + if (conn_flags & MQTT_CONN_HAS_WILL) { + PUSH16(p, will_topic_len); + PUSH_N(p, cli->will->topic, will_topic_len); + PUSH16(p, will_payload_len); + PUSH_N(p, cli->will->payload, will_payload_len); + } + if (conn_flags & MQTT_CONN_HAS_USERNAME) { + PUSH16(p, username_len); + PUSH_N(p, cli->username, username_len); + } + if (conn_flags & MQTT_CONN_HAS_PASSWORD) { + PUSH16(p, password_len); + PUSH_N(p, cli->password, password_len); + } + + int nwrite = mqtt_client_send(cli, buf, p - buf); + HV_STACK_FREE(buf); + return nwrite < 0 ? nwrite : 0; +} + +static void reconnect_timer_cb(htimer_t* timer) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(timer); + if (cli == NULL) return; + cli->reconn_timer = NULL; + mqtt_client_reconnect(cli); +} + +static void on_close(hio_t* io) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + cli->connected = 0; + if (cli->cb) { + cli->head.type = MQTT_TYPE_DISCONNECT; + cli->cb(cli, cli->head.type); + } + // reconnect + if (cli->reconn_setting && reconn_setting_can_retry(cli->reconn_setting)) { + uint32_t delay = reconn_setting_calc_delay(cli->reconn_setting); + cli->reconn_timer = htimer_add(cli->loop, reconnect_timer_cb, delay, 1); + hevent_set_userdata(cli->reconn_timer, cli); + } +} + +static void on_packet(hio_t* io, void* buf, int len) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + unsigned char* p = (unsigned char*)buf; + unsigned char* end = p + len; + memset(&cli->head, 0, sizeof(mqtt_head_t)); + int headlen = mqtt_head_unpack(&cli->head, p, len); + if (headlen <= 0) return; + p += headlen; + switch (cli->head.type) { + // case MQTT_TYPE_CONNECT: + case MQTT_TYPE_CONNACK: + { + if (cli->head.length < 2) { + hloge("MQTT CONNACK malformed!"); + hio_close(io); + return; + } + unsigned char conn_flags = 0, rc = 0; + POP8(p, conn_flags); + POP8(p, rc); + if (rc != MQTT_CONNACK_ACCEPTED) { + cli->error = rc; + hloge("MQTT CONNACK error=%d", cli->error); + hio_close(io); + return; + } + cli->connected = 1; + if (cli->keepalive) { + cli->ping_cnt = 0; + hio_set_heartbeat(io, cli->keepalive * 1000, mqtt_send_ping); + } + } + break; + case MQTT_TYPE_PUBLISH: + { + if (cli->head.length < 2) { + hloge("MQTT PUBLISH malformed!"); + hio_close(io); + return; + } + memset(&cli->message, 0, sizeof(mqtt_message_t)); + POP16(p, cli->message.topic_len); + if (end - p < cli->message.topic_len) { + hloge("MQTT PUBLISH malformed!"); + hio_close(io); + return; + } + // NOTE: Not deep copy + cli->message.topic = (char*)p; + p += cli->message.topic_len; + if (cli->head.qos > 0) { + if (end - p < 2) { + hloge("MQTT PUBLISH malformed!"); + hio_close(io); + return; + } + POP16(p, cli->mid); + } + cli->message.payload_len = end - p; + if (cli->message.payload_len > 0) { + // NOTE: Not deep copy + cli->message.payload = (char*)p; + } + cli->message.qos = cli->head.qos; + if (cli->message.qos == 0) { + // Do nothing + } else if (cli->message.qos == 1) { + mqtt_send_head_with_mid(io, MQTT_TYPE_PUBACK, cli->mid); + } else if (cli->message.qos == 2) { + mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREC, cli->mid); + } + } + break; + case MQTT_TYPE_PUBACK: + case MQTT_TYPE_PUBREC: + case MQTT_TYPE_PUBREL: + case MQTT_TYPE_PUBCOMP: + { + if (cli->head.length < 2) { + hloge("MQTT PUBACK malformed!"); + hio_close(io); + return; + } + POP16(p, cli->mid); + if (cli->head.type == MQTT_TYPE_PUBREC) { + mqtt_send_head_with_mid(io, MQTT_TYPE_PUBREL, cli->mid); + } else if (cli->head.type == MQTT_TYPE_PUBREL) { + mqtt_send_head_with_mid(io, MQTT_TYPE_PUBCOMP, cli->mid); + } + } + break; + // case MQTT_TYPE_SUBSCRIBE: + // break; + case MQTT_TYPE_SUBACK: + { + if (cli->head.length < 2) { + hloge("MQTT SUBACK malformed!"); + hio_close(io); + return; + } + POP16(p, cli->mid); + } + break; + // case MQTT_TYPE_UNSUBSCRIBE: + // break; + case MQTT_TYPE_UNSUBACK: + { + if (cli->head.length < 2) { + hloge("MQTT UNSUBACK malformed!"); + hio_close(io); + return; + } + POP16(p, cli->mid); + } + break; + case MQTT_TYPE_PINGREQ: + // printf("recv ping\n"); + // printf("send pong\n"); + mqtt_send_pong(io); + return; + case MQTT_TYPE_PINGRESP: + // printf("recv pong\n"); + cli->ping_cnt = 0; + return; + case MQTT_TYPE_DISCONNECT: + hio_close(io); + return; + default: + hloge("MQTT client received wrong type=%d", (int)cli->head.type); + hio_close(io); + return; + } + + if (cli->cb) { + cli->cb(cli, cli->head.type); + } +} + +static void on_connect(hio_t* io) { + mqtt_client_t* cli = (mqtt_client_t*)hevent_userdata(io); + if (cli->cb) { + cli->head.type = MQTT_TYPE_CONNECT; + cli->cb(cli, cli->head.type); + } + if (cli->reconn_setting) { + reconn_setting_reset(cli->reconn_setting); + } + + static unpack_setting_t mqtt_unpack_setting; + mqtt_unpack_setting.mode = UNPACK_BY_LENGTH_FIELD; + mqtt_unpack_setting.package_max_length = DEFAULT_MQTT_PACKAGE_MAX_LENGTH; + mqtt_unpack_setting.body_offset = 2; + mqtt_unpack_setting.length_field_offset = 1; + mqtt_unpack_setting.length_field_bytes = 1; + mqtt_unpack_setting.length_field_coding = ENCODE_BY_VARINT; + hio_set_unpack(io, &mqtt_unpack_setting); + + // start recv packet + hio_setcb_read(io, on_packet); + hio_read(io); + + mqtt_client_login(cli); +} + +mqtt_client_t* mqtt_client_new(hloop_t* loop) { + if (loop == NULL) { + loop = hloop_new(HLOOP_FLAG_AUTO_FREE); + if (loop == NULL) return NULL; + } + mqtt_client_t* cli = NULL; + HV_ALLOC_SIZEOF(cli); + if (cli == NULL) return NULL; + cli->loop = loop; + cli->protocol_version = MQTT_PROTOCOL_V311; + cli->keepalive = DEFAULT_MQTT_KEEPALIVE; + hmutex_init(&cli->mutex_); + return cli; +} + +void mqtt_client_free(mqtt_client_t* cli) { + if (!cli) return; + hmutex_destroy(&cli->mutex_); + if (cli->ssl_ctx && cli->alloced_ssl_ctx) { + hssl_ctx_free(cli->ssl_ctx); + cli->ssl_ctx = NULL; + } + HV_FREE(cli->reconn_setting); + HV_FREE(cli->will); + HV_FREE(cli); +} + +void mqtt_client_run (mqtt_client_t* cli) { + if (!cli || !cli->loop) return; + hloop_run(cli->loop); +} + +void mqtt_client_stop(mqtt_client_t* cli) { + if (!cli || !cli->loop) return; + hloop_stop(cli->loop); +} + +void mqtt_client_set_id(mqtt_client_t* cli, const char* id) { + if (!cli || !id) return; + hv_strncpy(cli->client_id, id, sizeof(cli->client_id)); +} + +void mqtt_client_set_will(mqtt_client_t* cli, mqtt_message_t* will) { + if (!cli || !will) return; + if (cli->will == NULL) { + HV_ALLOC_SIZEOF(cli->will); + } + memcpy(cli->will, will, sizeof(mqtt_message_t)); +} + +void mqtt_client_set_auth(mqtt_client_t* cli, const char* username, const char* password) { + if (!cli) return; + if (username) { + hv_strncpy(cli->username, username, sizeof(cli->username)); + } + if (password) { + hv_strncpy(cli->password, password, sizeof(cli->password)); + } +} + +void mqtt_client_set_callback(mqtt_client_t* cli, mqtt_client_cb cb) { + if (!cli) return; + cli->cb = cb; +} + +void mqtt_client_set_userdata(mqtt_client_t* cli, void* userdata) { + if (!cli) return; + cli->userdata = userdata; +} + +void* mqtt_client_get_userdata(mqtt_client_t* cli) { + if (!cli) return NULL; + return cli->userdata; +} + +int mqtt_client_get_last_error(mqtt_client_t* cli) { + if (!cli) return -1; + return cli->error; +} + +int mqtt_client_set_ssl_ctx(mqtt_client_t* cli, hssl_ctx_t ssl_ctx) { + cli->ssl_ctx = ssl_ctx; + return 0; +} + +int mqtt_client_new_ssl_ctx(mqtt_client_t* cli, hssl_ctx_opt_t* opt) { + opt->endpoint = HSSL_CLIENT; + hssl_ctx_t ssl_ctx = hssl_ctx_new(opt); + if (ssl_ctx == NULL) return ERR_NEW_SSL_CTX; + cli->alloced_ssl_ctx = true; + return mqtt_client_set_ssl_ctx(cli, ssl_ctx); +} + +int mqtt_client_set_reconnect(mqtt_client_t* cli, reconn_setting_t* reconn) { + if (reconn == NULL) { + HV_FREE(cli->reconn_setting); + return 0; + } + if (cli->reconn_setting == NULL) { + HV_ALLOC_SIZEOF(cli->reconn_setting); + } + *cli->reconn_setting = *reconn; + return 0; +} + +int mqtt_client_reconnect(mqtt_client_t* cli) { + mqtt_client_connect(cli, cli->host, cli->port, cli->ssl); + return 0; +} + +void mqtt_client_set_connect_timeout(mqtt_client_t* cli, int ms) { + cli->connect_timeout = ms; +} + +int mqtt_client_connect(mqtt_client_t* cli, const char* host, int port, int ssl) { + if (!cli) return -1; + hv_strncpy(cli->host, host, sizeof(cli->host)); + cli->port = port; + cli->ssl = ssl; + hio_t* io = hio_create_socket(cli->loop, host, port, HIO_TYPE_TCP, HIO_CLIENT_SIDE); + if (io == NULL) return -1; + if (ssl) { + if (cli->ssl_ctx) { + hio_set_ssl_ctx(io, cli->ssl_ctx); + } + hio_enable_ssl(io); + } + if (cli->connect_timeout > 0) { + hio_set_connect_timeout(io, cli->connect_timeout); + } + cli->io = io; + hevent_set_userdata(io, cli); + hio_setcb_connect(io, on_connect); + hio_setcb_close(io, on_close); + return hio_connect(io); +} + +bool mqtt_client_is_connected(mqtt_client_t* cli) { + return cli && cli->connected; +} + +int mqtt_client_disconnect(mqtt_client_t* cli) { + if (!cli || !cli->io) return -1; + // cancel reconnect first + mqtt_client_set_reconnect(cli, NULL); + mqtt_send_disconnect(cli->io); + return hio_close(cli->io); +} + +int mqtt_client_publish(mqtt_client_t* cli, mqtt_message_t* msg) { + if (!cli || !cli->io || !msg) return -1; + if (!cli->connected) return -2; + int topic_len = msg->topic_len ? msg->topic_len : strlen(msg->topic); + int payload_len = msg->payload_len ? msg->payload_len : strlen(msg->payload); + int len = 2 + topic_len + payload_len; + if (msg->qos > 0) len += 2; // mid + unsigned short mid = 0; + + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = MQTT_TYPE_PUBLISH; + head.qos = msg->qos & 3; + head.retain = msg->retain; + head.length = len; + int buflen = mqtt_estimate_length(&head); + // NOTE: send payload alone + buflen -= payload_len; + unsigned char* buf = NULL; + HV_STACK_ALLOC(buf, buflen); + unsigned char* p = buf; + int headlen = mqtt_head_pack(&head, p); + p += headlen; + PUSH16(p, topic_len); + PUSH_N(p, msg->topic, topic_len); + if (msg->qos) { + mid = mqtt_next_mid(); + PUSH16(p, mid); + } + + hmutex_lock(&cli->mutex_); + // send head + topic + mid + int nwrite = hio_write(cli->io, buf, p - buf); + HV_STACK_FREE(buf); + if (nwrite < 0) { + goto unlock; + } + + // send payload + nwrite = hio_write(cli->io, msg->payload, payload_len); + +unlock: + hmutex_unlock(&cli->mutex_); + return nwrite < 0 ? nwrite : mid; +} + +int mqtt_client_subscribe(mqtt_client_t* cli, const char* topic, int qos) { + if (!cli || !cli->io || !topic) return -1; + if (!cli->connected) return -2; + int topic_len = strlen(topic); + int len = 2 + 2 + topic_len + 1; + + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = MQTT_TYPE_SUBSCRIBE; + head.qos = 1; + head.length = len; + int buflen = mqtt_estimate_length(&head); + unsigned char* buf = NULL; + HV_STACK_ALLOC(buf, buflen); + unsigned char* p = buf; + int headlen = mqtt_head_pack(&head, p); + p += headlen; + unsigned short mid = mqtt_next_mid(); + PUSH16(p, mid); + PUSH16(p, topic_len); + PUSH_N(p, topic, topic_len); + PUSH8(p, qos & 3); + // send head + mid + topic + qos + int nwrite = mqtt_client_send(cli, buf, p - buf); + HV_STACK_FREE(buf); + return nwrite < 0 ? nwrite : mid; +} + +int mqtt_client_unsubscribe(mqtt_client_t* cli, const char* topic) { + if (!cli || !cli->io || !topic) return -1; + if (!cli->connected) return -2; + int topic_len = strlen(topic); + int len = 2 + 2 + topic_len; + + mqtt_head_t head; + memset(&head, 0, sizeof(head)); + head.type = MQTT_TYPE_UNSUBSCRIBE; + head.qos = 1; + head.length = len; + int buflen = mqtt_estimate_length(&head); + unsigned char* buf = NULL; + HV_STACK_ALLOC(buf, buflen); + unsigned char* p = buf; + int headlen = mqtt_head_pack(&head, p); + p += headlen; + unsigned short mid = mqtt_next_mid(); + PUSH16(p, mid); + PUSH16(p, topic_len); + PUSH_N(p, topic, topic_len); + // send head + mid + topic + int nwrite = mqtt_client_send(cli, buf, p - buf); + HV_STACK_FREE(buf); + return nwrite < 0 ? nwrite : mid; +} diff --git a/external/libhv/libhv-1.3.2/mqtt/mqtt_client.h b/external/libhv/libhv-1.3.2/mqtt/mqtt_client.h new file mode 100644 index 0000000..360f435 --- /dev/null +++ b/external/libhv/libhv-1.3.2/mqtt/mqtt_client.h @@ -0,0 +1,334 @@ +#ifndef HV_MQTT_CLIENT_H_ +#define HV_MQTT_CLIENT_H_ + +#include "mqtt_protocol.h" +#include "hloop.h" +#include "hssl.h" +#include "hmutex.h" + +#define DEFAULT_MQTT_KEEPALIVE 60 // s + +typedef struct mqtt_client_s mqtt_client_t; + +// @type mqtt_type_e +// @example examples/mqtt +typedef void (*mqtt_client_cb)(mqtt_client_t* cli, int type); + +struct mqtt_client_s { + // connect: host:port + char host[256]; + int port; + int connect_timeout; // ms + // reconnect + reconn_setting_t* reconn_setting; + // login: flags + keepalive + client_id + will + username + password + // flags + unsigned char protocol_version; // Default MQTT_PROTOCOL_V311 + unsigned char clean_session: 1; + unsigned char ssl: 1; // Read Only + unsigned char alloced_ssl_ctx: 1; // intern + unsigned char connected : 1; + unsigned short keepalive; + int ping_cnt; + char client_id[64]; + // will + mqtt_message_t* will; + // auth + char username[64]; + char password[64]; + // message + mqtt_head_t head; + int error; // for MQTT_TYPE_CONNACK + int mid; // for MQTT_TYPE_SUBACK, MQTT_TYPE_PUBACK + mqtt_message_t message; // for MQTT_TYPE_PUBLISH + // callback + mqtt_client_cb cb; + // userdata + void* userdata; + // privdata + hloop_t* loop; + hio_t* io; + htimer_t* reconn_timer; + // SSL/TLS + hssl_ctx_t ssl_ctx; + // thread-safe + hmutex_t mutex_; +}; + +BEGIN_EXTERN_C + +// hloop_new -> malloc(mqtt_client_t) +HV_EXPORT mqtt_client_t* mqtt_client_new(hloop_t* loop DEFAULT(NULL)); +// @see hloop_run +HV_EXPORT void mqtt_client_run (mqtt_client_t* cli); +// @see hloop_stop +HV_EXPORT void mqtt_client_stop(mqtt_client_t* cli); +// hloop_free -> free(mqtt_client_t) +HV_EXPORT void mqtt_client_free(mqtt_client_t* cli); + +// id +HV_EXPORT void mqtt_client_set_id(mqtt_client_t* cli, const char* id); + +// will +HV_EXPORT void mqtt_client_set_will(mqtt_client_t* cli, + mqtt_message_t* will); + +// auth +HV_EXPORT void mqtt_client_set_auth(mqtt_client_t* cli, + const char* username, const char* password); + +// callback +HV_EXPORT void mqtt_client_set_callback(mqtt_client_t* cli, mqtt_client_cb cb); + +// userdata +HV_EXPORT void mqtt_client_set_userdata(mqtt_client_t* cli, void* userdata); +HV_EXPORT void* mqtt_client_get_userdata(mqtt_client_t* cli); + +// error +HV_EXPORT int mqtt_client_get_last_error(mqtt_client_t* cli); + +// SSL/TLS +HV_EXPORT int mqtt_client_set_ssl_ctx(mqtt_client_t* cli, hssl_ctx_t ssl_ctx); +// hssl_ctx_new(opt) -> mqtt_client_set_ssl_ctx +HV_EXPORT int mqtt_client_new_ssl_ctx(mqtt_client_t* cli, hssl_ctx_opt_t* opt); + +// reconnect +HV_EXPORT int mqtt_client_set_reconnect(mqtt_client_t* cli, + reconn_setting_t* reconn); +HV_EXPORT int mqtt_client_reconnect(mqtt_client_t* cli); + +// connect +// hio_create_socket -> hio_connect -> +// on_connect -> mqtt_client_login -> +// on_connack +HV_EXPORT void mqtt_client_set_connect_timeout(mqtt_client_t* cli, int ms); +HV_EXPORT int mqtt_client_connect(mqtt_client_t* cli, + const char* host, + int port DEFAULT(DEFAULT_MQTT_PORT), + int ssl DEFAULT(0)); +HV_EXPORT bool mqtt_client_is_connected(mqtt_client_t* cli); + +// disconnect +// @see hio_close +HV_EXPORT int mqtt_client_disconnect(mqtt_client_t* cli); + +// publish +HV_EXPORT int mqtt_client_publish(mqtt_client_t* cli, + mqtt_message_t* msg); + +// subscribe +HV_EXPORT int mqtt_client_subscribe(mqtt_client_t* cli, + const char* topic, int qos DEFAULT(0)); + +// unsubscribe +HV_EXPORT int mqtt_client_unsubscribe(mqtt_client_t* cli, + const char* topic); + +END_EXTERN_C + +#ifdef __cplusplus + +#include +#include +#include + +namespace hv { + +// @usage examples/mqtt/mqtt_client_test.cpp +class MqttClient { +public: + mqtt_client_t* client; + // callbacks + typedef std::function MqttCallback; + typedef std::function MqttMessageCallback; + MqttCallback onConnect; + MqttCallback onClose; + MqttMessageCallback onMessage; + + MqttClient(hloop_t* loop = NULL) { + client = mqtt_client_new(loop); + } + + ~MqttClient() { + if (client) { + mqtt_client_free(client); + client = NULL; + } + } + + void run() { + mqtt_client_set_callback(client, on_mqtt); + mqtt_client_set_userdata(client, this); + mqtt_client_run(client); + } + + void stop() { + mqtt_client_stop(client); + } + + void setID(const char* id) { + mqtt_client_set_id(client, id); + } + + void setWill(mqtt_message_t* will) { + mqtt_client_set_will(client, will); + } + + void setAuth(const char* username, const char* password) { + mqtt_client_set_auth(client, username, password); + } + + void setPingInterval(int sec) { + client->keepalive = sec; + } + + int lastError() { + return mqtt_client_get_last_error(client); + } + + // SSL/TLS + int setSslCtx(hssl_ctx_t ssl_ctx) { + return mqtt_client_set_ssl_ctx(client, ssl_ctx); + } + int newSslCtx(hssl_ctx_opt_t* opt) { + return mqtt_client_new_ssl_ctx(client, opt); + } + + void setReconnect(reconn_setting_t* reconn) { + mqtt_client_set_reconnect(client, reconn); + } + + void setConnectTimeout(int ms) { + mqtt_client_set_connect_timeout(client, ms); + } + + int connect(const char* host, int port = DEFAULT_MQTT_PORT, int ssl = 0) { + return mqtt_client_connect(client, host, port, ssl); + } + + int reconnect() { + return mqtt_client_reconnect(client); + } + + int disconnect() { + return mqtt_client_disconnect(client); + } + + bool isConnected() { + return mqtt_client_is_connected(client); + } + + int publish(mqtt_message_t* msg, MqttCallback ack_cb = NULL) { + int mid = mqtt_client_publish(client, msg); + if (msg->qos > 0 && mid >= 0 && ack_cb) { + setAckCallback(mid, ack_cb); + } + return mid; + } + + int publish(const std::string& topic, const std::string& payload, int qos = 0, int retain = 0, MqttCallback ack_cb = NULL) { + mqtt_message_t msg; + memset(&msg, 0, sizeof(msg)); + msg.topic_len = topic.size(); + msg.topic = topic.c_str(); + msg.payload_len = payload.size(); + msg.payload = payload.c_str(); + msg.qos = qos; + msg.retain = retain; + return publish(&msg, ack_cb); + } + + int subscribe(const char* topic, int qos = 0, MqttCallback ack_cb = NULL) { + int mid = mqtt_client_subscribe(client, topic, qos); + if (qos > 0 && mid >= 0 && ack_cb) { + setAckCallback(mid, ack_cb); + } + return mid; + } + + int unsubscribe(const char* topic, MqttCallback ack_cb = NULL) { + int mid = mqtt_client_unsubscribe(client, topic); + if (mid >= 0 && ack_cb) { + setAckCallback(mid, ack_cb); + } + return mid; + } + +protected: + void setAckCallback(int mid, MqttCallback cb) { + ack_cbs_mutex.lock(); + ack_cbs[mid] = std::move(cb); + ack_cbs_mutex.unlock(); + } + + void invokeAckCallback(int mid) { + MqttCallback ack_cb = NULL; + ack_cbs_mutex.lock(); + auto iter = ack_cbs.find(mid); + if (iter != ack_cbs.end()) { + ack_cb = std::move(iter->second); + ack_cbs.erase(iter); + } + ack_cbs_mutex.unlock(); + if (ack_cb) ack_cb(this); + } + + static void on_mqtt(mqtt_client_t* cli, int type) { + MqttClient* client = (MqttClient*)mqtt_client_get_userdata(cli); + // printf("on_mqtt type=%d\n", type); + switch(type) { + case MQTT_TYPE_CONNECT: + // printf("mqtt connected!\n"); + break; + case MQTT_TYPE_DISCONNECT: + // printf("mqtt disconnected!\n"); + if (client->onClose) { + client->onClose(client); + } + break; + case MQTT_TYPE_CONNACK: + // printf("mqtt connack!\n"); + if (client->onConnect) { + client->onConnect(client); + } + break; + case MQTT_TYPE_PUBLISH: + if (client->onMessage) { + client->onMessage(client, &cli->message); + } + break; + case MQTT_TYPE_PUBACK: /* qos = 1 */ + // printf("mqtt puback mid=%d\n", cli->mid); + client->invokeAckCallback(cli->mid); + break; + case MQTT_TYPE_PUBREC: /* qos = 2 */ + // printf("mqtt pubrec mid=%d\n", cli->mid); + // wait MQTT_TYPE_PUBCOMP + break; + case MQTT_TYPE_PUBCOMP: /* qos = 2 */ + // printf("mqtt pubcomp mid=%d\n", cli->mid); + client->invokeAckCallback(cli->mid); + break; + case MQTT_TYPE_SUBACK: + // printf("mqtt suback mid=%d\n", cli->mid); + client->invokeAckCallback(cli->mid); + break; + case MQTT_TYPE_UNSUBACK: + // printf("mqtt unsuback mid=%d\n", cli->mid); + client->invokeAckCallback(cli->mid); + break; + default: + break; + } + } + +private: + // mid => ack callback + std::map ack_cbs; + std::mutex ack_cbs_mutex; +}; + +} +#endif + +#endif // HV_MQTT_CLIENT_H_ diff --git a/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.c b/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.c new file mode 100644 index 0000000..f556097 --- /dev/null +++ b/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.c @@ -0,0 +1,22 @@ +#include "mqtt_protocol.h" +#include "hmath.h" + +int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]) { + buf[0] = (head->type << 4) | + (head->dup << 3) | + (head->qos << 1) | + (head->retain); + int bytes = varint_encode(head->length, buf + 1); + return 1 + bytes; +} + +int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len) { + head->type = (buf[0] >> 4) & 0x0F; + head->dup = (buf[0] >> 3) & 0x01; + head->qos = (buf[0] >> 1) & 0x03; + head->retain = buf[0] & 0x01; + int bytes = len - 1; + head->length = varint_decode(buf + 1, &bytes); + if (bytes <= 0) return bytes; + return 1 + bytes; +} diff --git a/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.h b/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.h new file mode 100644 index 0000000..57343e1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/mqtt/mqtt_protocol.h @@ -0,0 +1,82 @@ +#ifndef HV_MQTT_PROTOCOL_H_ +#define HV_MQTT_PROTOCOL_H_ + +#include "hexport.h" + +#define DEFAULT_MQTT_PORT 1883 + +#define MQTT_PROTOCOL_V31 3 +#define MQTT_PROTOCOL_V311 4 +#define MQTT_PROTOCOL_V5 5 // Not yet supproted + +#define MQTT_PROTOCOL_NAME "MQTT" +#define MQTT_PROTOCOL_NAME_v31 "MQIsdp" + +/* + * connect flags + * 0 1 2 3-4 5 6 7 + * reserved clean_session has_will will_qos will_retain has_password has_username + */ +#define MQTT_CONN_CLEAN_SESSION 0x02 +#define MQTT_CONN_HAS_WILL 0x04 +#define MQTT_CONN_WILL_RETAIN 0x20 +#define MQTT_CONN_HAS_PASSWORD 0x40 +#define MQTT_CONN_HAS_USERNAME 0x80 + +typedef enum { + MQTT_TYPE_CONNECT = 1, + MQTT_TYPE_CONNACK = 2, + MQTT_TYPE_PUBLISH = 3, + MQTT_TYPE_PUBACK = 4, + MQTT_TYPE_PUBREC = 5, + MQTT_TYPE_PUBREL = 6, + MQTT_TYPE_PUBCOMP = 7, + MQTT_TYPE_SUBSCRIBE = 8, + MQTT_TYPE_SUBACK = 9, + MQTT_TYPE_UNSUBSCRIBE = 10, + MQTT_TYPE_UNSUBACK = 11, + MQTT_TYPE_PINGREQ = 12, + MQTT_TYPE_PINGRESP = 13, + MQTT_TYPE_DISCONNECT = 14, +} mqtt_type_e; + +typedef enum { + MQTT_CONNACK_ACCEPTED = 0, + MQTT_CONNACK_REFUSED_PROTOCOL_VERSION = 1, + MQTT_CONNACK_REFUSED_IDENTIFIER_REJECTED = 2, + MQTT_CONNACK_REFUSED_SERVER_UNAVAILABLE = 3, + MQTT_CONNACK_REFUSED_BAD_USERNAME_PASSWORD = 4, + MQTT_CONNACK_REFUSED_NOT_AUTHORIZED = 5, +} mqtt_connack_e; + +typedef struct mqtt_head_s { + unsigned char type: 4; + unsigned char dup: 1; + unsigned char qos: 2; + unsigned char retain: 1; + unsigned int length; +} mqtt_head_t; + +typedef struct mqtt_message_s { + unsigned int topic_len; + const char* topic; + unsigned int payload_len; + const char* payload; + unsigned char qos; + unsigned char retain; +} mqtt_message_t; + +BEGIN_EXTERN_C + +#define DEFAULT_MQTT_PACKAGE_MAX_LENGTH (1 << 28) // 256M +HV_INLINE int mqtt_estimate_length(mqtt_head_t* head) { + // 28 bits => 4*7 bits varint + return 1 + 4 + head->length; +} + +HV_EXPORT int mqtt_head_pack(mqtt_head_t* head, unsigned char buf[]); +HV_EXPORT int mqtt_head_unpack(mqtt_head_t* head, const unsigned char* buf, int len); + +END_EXTERN_C + +#endif // HV_MQTT_PROTOCOL_H_ diff --git a/external/libhv/libhv-1.3.2/protocol/README.md b/external/libhv/libhv-1.3.2/protocol/README.md new file mode 100644 index 0000000..3d51514 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/README.md @@ -0,0 +1,10 @@ +## 目录结构 + +``` +. +├── dns.h DNS协议 +├── ftp.h FTP协议 +├── icmp.h ICMP协议 +└── smtp.h SMTP协议 + +``` diff --git a/external/libhv/libhv-1.3.2/protocol/dns.c b/external/libhv/libhv-1.3.2/protocol/dns.c new file mode 100644 index 0000000..4fa55d3 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/dns.c @@ -0,0 +1,336 @@ +#include "dns.h" + +#include "hdef.h" +#include "hsocket.h" +#include "herr.h" + +void dns_free(dns_t* dns) { + SAFE_FREE(dns->questions); + SAFE_FREE(dns->answers); + SAFE_FREE(dns->authorities); + SAFE_FREE(dns->addtionals); +} + +// www.example.com => 3www7example3com +int dns_name_encode(const char* domain, char* buf) { + const char* p = domain; + char* plen = buf++; + int buflen = 1; + int len = 0; + while (*p != '\0') { + if (*p != '.') { + ++len; + *buf = *p; + } + else { + *plen = len; + //printf("len=%d\n", len); + plen = buf; + len = 0; + } + ++p; + ++buf; + ++buflen; + } + *plen = len; + //printf("len=%d\n", len); + *buf = '\0'; + if (len != 0) { + ++buflen; // include last '\0' + } + return buflen; +} + +// 3www7example3com => www.example.com +int dns_name_decode(const char* buf, char* domain) { + const char* p = buf; + int len = *p++; + //printf("len=%d\n", len); + int buflen = 1; + while (*p != '\0') { + if (len-- == 0) { + len = *p; + //printf("len=%d\n", len); + *domain = '.'; + } + else { + *domain = *p; + } + ++p; + ++domain; + ++buflen; + } + *domain = '\0'; + ++buflen; // include last '\0' + return buflen; +} + +int dns_rr_pack(dns_rr_t* rr, char* buf, int len) { + char* p = buf; + char encoded_name[256]; + int encoded_namelen = dns_name_encode(rr->name, encoded_name); + int packetlen = encoded_namelen + 2 + 2 + (rr->data ? (4+2+rr->datalen) : 0); + if (len < packetlen) { + return -1; + } + + memcpy(p, encoded_name, encoded_namelen); + p += encoded_namelen; + uint16_t* pushort = (uint16_t*)p; + *pushort = htons(rr->rtype); + p += 2; + pushort = (uint16_t*)p; + *pushort = htons(rr->rclass); + p += 2; + + // ... + if (rr->datalen && rr->data) { + uint32_t* puint = (uint32_t*)p; + *puint = htonl(rr->ttl); + p += 4; + pushort = (uint16_t*)p; + *pushort = htons(rr->datalen); + p += 2; + memcpy(p, rr->data, rr->datalen); + p += rr->datalen; + } + return packetlen; +} + +int dns_rr_unpack(char* buf, int len, dns_rr_t* rr, int is_question) { + char* p = buf; + int off = 0; + int namelen = 0; + if (*(uint8_t*)p >= 192) { + // name off, we ignore + namelen = 2; + //uint16_t nameoff = (*(uint8_t*)p - 192) * 256 + *(uint8_t*)(p+1); + } + else { + namelen = dns_name_decode(buf, rr->name); + } + if (namelen < 0) return -1; + p += namelen; + off += namelen; + + if (len < off + 4) return -1; + uint16_t* pushort = (uint16_t*)p; + rr->rtype = ntohs(*pushort); + p += 2; + pushort = (uint16_t*)p; + rr->rclass = ntohs(*pushort); + p += 2; + off += 4; + + if (!is_question) { + if (len < off + 6) return -1; + uint32_t* puint = (uint32_t*)p; + rr->ttl = ntohl(*puint); + p += 4; + pushort = (uint16_t*)p; + rr->datalen = ntohs(*pushort); + p += 2; + off += 6; + if (len < off + rr->datalen) return -1; + rr->data = p; + p += rr->datalen; + off += rr->datalen; + } + return off; +} + +int dns_pack(dns_t* dns, char* buf, int len) { + if (len < sizeof(dnshdr_t)) return -1; + int off = 0; + dnshdr_t* hdr = &dns->hdr; + dnshdr_t htonhdr = dns->hdr; + htonhdr.transaction_id = htons(hdr->transaction_id); + htonhdr.nquestion = htons(hdr->nquestion); + htonhdr.nanswer = htons(hdr->nanswer); + htonhdr.nauthority = htons(hdr->nauthority); + htonhdr.naddtional = htons(hdr->naddtional); + memcpy(buf, &htonhdr, sizeof(dnshdr_t)); + off += sizeof(dnshdr_t); + int i; + for (i = 0; i < hdr->nquestion; ++i) { + int packetlen = dns_rr_pack(dns->questions+i, buf+off, len-off); + if (packetlen < 0) return -1; + off += packetlen; + } + for (i = 0; i < hdr->nanswer; ++i) { + int packetlen = dns_rr_pack(dns->answers+i, buf+off, len-off); + if (packetlen < 0) return -1; + off += packetlen; + } + for (i = 0; i < hdr->nauthority; ++i) { + int packetlen = dns_rr_pack(dns->authorities+i, buf+off, len-off); + if (packetlen < 0) return -1; + off += packetlen; + } + for (i = 0; i < hdr->naddtional; ++i) { + int packetlen = dns_rr_pack(dns->addtionals+i, buf+off, len-off); + if (packetlen < 0) return -1; + off += packetlen; + } + return off; +} + +int dns_unpack(char* buf, int len, dns_t* dns) { + memset(dns, 0, sizeof(dns_t)); + if (len < sizeof(dnshdr_t)) return -1; + int off = 0; + dnshdr_t* hdr = &dns->hdr; + memcpy(hdr, buf, sizeof(dnshdr_t)); + off += sizeof(dnshdr_t); + hdr->transaction_id = ntohs(hdr->transaction_id); + hdr->nquestion = ntohs(hdr->nquestion); + hdr->nanswer = ntohs(hdr->nanswer); + hdr->nauthority = ntohs(hdr->nauthority); + hdr->naddtional = ntohs(hdr->naddtional); + int i; + if (hdr->nquestion) { + int bytes = hdr->nquestion * sizeof(dns_rr_t); + SAFE_ALLOC(dns->questions, bytes); + for (i = 0; i < hdr->nquestion; ++i) { + int packetlen = dns_rr_unpack(buf+off, len-off, dns->questions+i, 1); + if (packetlen < 0) return -1; + off += packetlen; + } + } + if (hdr->nanswer) { + int bytes = hdr->nanswer * sizeof(dns_rr_t); + SAFE_ALLOC(dns->answers, bytes); + for (i = 0; i < hdr->nanswer; ++i) { + int packetlen = dns_rr_unpack(buf+off, len-off, dns->answers+i, 0); + if (packetlen < 0) return -1; + off += packetlen; + } + } + if (hdr->nauthority) { + int bytes = hdr->nauthority * sizeof(dns_rr_t); + SAFE_ALLOC(dns->authorities, bytes); + for (i = 0; i < hdr->nauthority; ++i) { + int packetlen = dns_rr_unpack(buf+off, len-off, dns->authorities+i, 0); + if (packetlen < 0) return -1; + off += packetlen; + } + } + if (hdr->naddtional) { + int bytes = hdr->naddtional * sizeof(dns_rr_t); + SAFE_ALLOC(dns->addtionals, bytes); + for (i = 0; i < hdr->naddtional; ++i) { + int packetlen = dns_rr_unpack(buf+off, len-off, dns->addtionals+i, 0); + if (packetlen < 0) return -1; + off += packetlen; + } + } + return off; +} + +// dns_pack -> sendto -> recvfrom -> dns_unpack +int dns_query(dns_t* query, dns_t* response, const char* nameserver) { + char buf[1024]; + int buflen = sizeof(buf); + buflen = dns_pack(query, buf, buflen); + if (buflen < 0) { + return buflen; + } +#ifdef OS_WIN + WSAInit(); +#endif + int sockfd = socket(AF_INET, SOCK_DGRAM, 0); + if (sockfd < 0) { + perror("socket"); + return ERR_SOCKET; + } + so_sndtimeo(sockfd, 5000); + so_rcvtimeo(sockfd, 5000); + int ret = 0; + int nsend, nrecv; + int nparse; + struct sockaddr_in addr; + socklen_t addrlen = sizeof(addr); + memset(&addr, 0, addrlen); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = inet_addr(nameserver); + addr.sin_port = htons(DNS_PORT); + nsend = sendto(sockfd, buf, buflen, 0, (struct sockaddr*)&addr, addrlen); + if (nsend != buflen) { + ret = ERR_SENDTO; + goto error; + } + nrecv = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen); + if (nrecv <= 0) { + ret = ERR_RECVFROM; + goto error; + } + + nparse = dns_unpack(buf, nrecv, response); + if (nparse != nrecv) { + ret = -ERR_INVALID_PACKAGE; + goto error; + } + +error: + if (sockfd != INVALID_SOCKET) { + closesocket(sockfd); + } + return ret; +} + +int nslookup(const char* domain, uint32_t* addrs, int naddr, const char* nameserver) { + dns_t query; + memset(&query, 0, sizeof(query)); + query.hdr.transaction_id = getpid(); + query.hdr.qr = DNS_QUERY; + query.hdr.rd = 1; + query.hdr.nquestion = 1; + + dns_rr_t question; + memset(&question, 0, sizeof(question)); + strncpy(question.name, domain, sizeof(question.name)); + question.rtype = DNS_TYPE_A; + question.rclass = DNS_CLASS_IN; + + query.questions = &question; + + dns_t resp; + memset(&resp, 0, sizeof(resp)); + int ret = dns_query(&query, &resp, nameserver); + if (ret != 0) { + return ret; + } + + dns_rr_t* rr = resp.answers; + int addr_cnt = 0; + if (resp.hdr.transaction_id != query.hdr.transaction_id || + resp.hdr.qr != DNS_RESPONSE || + resp.hdr.rcode != 0) { + ret = -ERR_MISMATCH; + goto end; + } + + if (resp.hdr.nanswer == 0) { + ret = 0; + goto end; + } + + for (int i = 0; i < resp.hdr.nanswer; ++i, ++rr) { + if (rr->rtype == DNS_TYPE_A) { + if (addr_cnt < naddr && rr->datalen == 4) { + memcpy(addrs+addr_cnt, rr->data, 4); + } + ++addr_cnt; + } + /* + else if (rr->rtype == DNS_TYPE_CNAME) { + char name[256]; + dns_name_decode(rr->data, name); + } + */ + } + ret = addr_cnt; +end: + dns_free(&resp); + return ret; +} diff --git a/external/libhv/libhv-1.3.2/protocol/dns.h b/external/libhv/libhv-1.3.2/protocol/dns.h new file mode 100644 index 0000000..2bb9d43 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/dns.h @@ -0,0 +1,105 @@ +#ifndef HV_DNS_H_ +#define HV_DNS_H_ + +#include "hexport.h" +#include "hplatform.h" + +#define DNS_PORT 53 + +#define DNS_QUERY 0 +#define DNS_RESPONSE 1 + +#define DNS_TYPE_A 1 // ipv4 +#define DNS_TYPE_NS 2 +#define DNS_TYPE_CNAME 5 +#define DNS_TYPE_SOA 6 +#define DNS_TYPE_WKS 11 +#define DNS_TYPE_PTR 12 +#define DNS_TYPE_HINFO 13 +#define DNS_TYPE_MX 15 +#define DNS_TYPE_AAAA 28 // ipv6 +#define DNS_TYPE_AXFR 252 +#define DNS_TYPE_ANY 255 + +#define DNS_CLASS_IN 1 + +#define DNS_NAME_MAXLEN 256 + +// sizeof(dnshdr_t) = 12 +typedef struct dnshdr_s { + uint16_t transaction_id; + // flags +#if BYTE_ORDER == LITTLE_ENDIAN + uint8_t rd:1; + uint8_t tc:1; + uint8_t aa:1; + uint8_t opcode:4; + uint8_t qr:1; + + uint8_t rcode:4; + uint8_t cd:1; + uint8_t ad:1; + uint8_t res:1; + uint8_t ra:1; +#elif BYTE_ORDER == BIG_ENDIAN + uint8_t qr:1; // DNS_QUERY or DNS_RESPONSE + uint8_t opcode:4; + uint8_t aa:1; // authoritative + uint8_t tc:1; // truncated + uint8_t rd:1; // recursion desired + + uint8_t ra:1; // recursion available + uint8_t res:1; // reserved + uint8_t ad:1; // authenticated data + uint8_t cd:1; // checking disable + uint8_t rcode:4; +#else +#error "BYTE_ORDER undefined!" +#endif + uint16_t nquestion; + uint16_t nanswer; + uint16_t nauthority; + uint16_t naddtional; +} dnshdr_t; + +typedef struct dns_rr_s { + char name[DNS_NAME_MAXLEN]; // original domain, such as www.example.com + uint16_t rtype; + uint16_t rclass; + uint32_t ttl; + uint16_t datalen; + char* data; +} dns_rr_t; + +typedef struct dns_s { + dnshdr_t hdr; + dns_rr_t* questions; + dns_rr_t* answers; + dns_rr_t* authorities; + dns_rr_t* addtionals; +} dns_t; + +BEGIN_EXTERN_C + +// www.example.com => 3www7example3com +HV_EXPORT int dns_name_encode(const char* domain, char* buf); +// 3www7example3com => www.example.com +HV_EXPORT int dns_name_decode(const char* buf, char* domain); + +HV_EXPORT int dns_rr_pack(dns_rr_t* rr, char* buf, int len); +HV_EXPORT int dns_rr_unpack(char* buf, int len, dns_rr_t* rr, int is_question); + +HV_EXPORT int dns_pack(dns_t* dns, char* buf, int len); +HV_EXPORT int dns_unpack(char* buf, int len, dns_t* dns); +// NOTE: free dns->rrs +HV_EXPORT void dns_free(dns_t* dns); + +// dns_pack -> sendto -> recvfrom -> dns_unpack +HV_EXPORT int dns_query(dns_t* query, dns_t* response, const char* nameserver DEFAULT("127.0.1.1")); + +// domain -> dns_t query; -> dns_query -> dns_t response; -> addrs +HV_EXPORT int nslookup(const char* domain, uint32_t* addrs, int naddr, const char* nameserver DEFAULT("127.0.1.1")); + +END_EXTERN_C + +#endif // HV_DNS_H_ diff --git a/external/libhv/libhv-1.3.2/protocol/ftp.c b/external/libhv/libhv-1.3.2/protocol/ftp.c new file mode 100644 index 0000000..7dcdba7 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/ftp.c @@ -0,0 +1,247 @@ +#include "ftp.h" +#include "hsocket.h" +#include "herr.h" + +const char* ftp_command_str(enum ftp_command cmd) { + switch (cmd) { +#define X(name) case FTP_##name: return #name; + FTP_COMMAND_MAP(X) +#undef X + default: return ""; + } +} + +const char* ftp_status_str(enum ftp_status status) { + switch (status) { +#define XXX(code, name, string) case FTP_STATUS_##name: return #string; + FTP_STATUS_MAP(XXX) +#undef XXX + default: return ""; + } +} + +int ftp_connect(ftp_handle_t* hftp, const char* host, int port) { + int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); + if (sockfd < 0) { + return sockfd; + } + so_sndtimeo(sockfd, 5000); + so_rcvtimeo(sockfd, 5000); + hftp->sockfd = sockfd; + int ret = 0; + int status_code = 0; + memset(hftp->recvbuf, 0, FTP_RECV_BUFSIZE); + int nrecv = recv(sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(hftp->recvbuf); + if (status_code != FTP_STATUS_READY) { + ret = status_code; + goto error; + } + return 0; + +error: + closesocket(sockfd); + return ret; +} + +int ftp_login(ftp_handle_t* hftp, const char* username, const char* password) { + int status_code = ftp_exec(hftp, "USER", username); + status_code = ftp_exec(hftp, "PASS", password); + return status_code == FTP_STATUS_LOGIN_OK ? 0 : status_code; +} + +int ftp_quit(ftp_handle_t* hftp) { + ftp_exec(hftp, "QUIT", NULL); + closesocket(hftp->sockfd); + return 0; +} + +int ftp_exec(ftp_handle_t* hftp, const char* cmd, const char* param) { + char buf[1024]; + int len = 0; + if (param && *param) { + len = snprintf(buf, sizeof(buf), "%s %s\r\n", cmd, param); + } + else { + len = snprintf(buf, sizeof(buf), "%s\r\n", cmd); + } + int nsend, nrecv; + int ret = 0; + nsend = send(hftp->sockfd, buf, len, 0); + if (nsend != len) { + ret = ERR_SEND; + goto error; + } + //printf("> %s", buf); + memset(hftp->recvbuf, 0, FTP_RECV_BUFSIZE); + nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + //printf("< %s", hftp->recvbuf); + return atoi(hftp->recvbuf); +error: + closesocket(hftp->sockfd); + return ret; +} + +static int ftp_parse_pasv(const char* resp, char* host, int* port) { + // 227 Entering Passive Mode (127,0,0,1,4,51) + const char* str = strchr(resp, '('); + if (str == NULL) { + return ERR_RESPONSE; + } + int arr[6]; + sscanf(str, "(%d,%d,%d,%d,%d,%d)", + &arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5]); + sprintf(host, "%d.%d.%d.%d", arr[0], arr[1], arr[2], arr[3]); + *port = arr[4] << 8 | arr[5]; + return 0; +} + +int ftp_download_with_cb(ftp_handle_t* hftp, const char* filepath, ftp_download_cb cb) { + int status_code = ftp_exec(hftp, "PASV", NULL); + if (status_code != FTP_STATUS_PASV) { + return status_code; + } + char host[64]; + int port = 0; + int ret = ftp_parse_pasv(hftp->recvbuf, host, &port); + if (ret != 0) { + return ret; + } + //ftp_exec(hftp, "RETR", filepath); + char request[1024]; + int len = snprintf(request, sizeof(request), "RETR %s\r\n", filepath); + int nsend = send(hftp->sockfd, request, len, 0); + if (nsend != len) { + closesocket(hftp->sockfd); + return ERR_SEND; + } + //printf("> %s", request); + int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); + if (sockfd < 0) { + return sockfd; + } + int nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + closesocket(hftp->sockfd); + return ERR_RECV; + } + //printf("< %s", hftp->recvbuf); + { + // you can create thread to recv data + char recvbuf[1024]; + int ntotal = 0; + while (1) { + nrecv = recv(sockfd, recvbuf, sizeof(recvbuf), 0); + if (cb) { + cb(hftp, recvbuf, nrecv); + } + if (nrecv <= 0) break; + ntotal += nrecv; + } + } + closesocket(sockfd); + nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + closesocket(hftp->sockfd); + return ERR_RECV; + } + //printf("< %s", hftp->recvbuf); + status_code = atoi(hftp->recvbuf); + return status_code == FTP_STATUS_TRANSFER_COMPLETE ? 0 : status_code; +} + +// local => remote +int ftp_upload(ftp_handle_t* hftp, const char* local_filepath, const char* remote_filepath) { + int status_code = ftp_exec(hftp, "PASV", NULL); + if (status_code != FTP_STATUS_PASV) { + return status_code; + } + char host[64]; + int port = 0; + int ret = ftp_parse_pasv(hftp->recvbuf, host, &port); + if (ret != 0) { + return ret; + } + //ftp_exec(hftp, "STOR", remote_filepath); + char request[1024]; + int len = snprintf(request, sizeof(request), "STOR %s\r\n", remote_filepath); + int nsend = send(hftp->sockfd, request, len, 0); + if (nsend != len) { + closesocket(hftp->sockfd); + return ERR_SEND; + } + //printf("> %s", request); + int sockfd = ConnectTimeout(host, port, DEFAULT_CONNECT_TIMEOUT); + if (sockfd < 0) { + return sockfd; + } + int nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + closesocket(hftp->sockfd); + return ERR_RECV; + } + //printf("< %s", hftp->recvbuf); + { + // you can create thread to send data + FILE* fp = fopen(local_filepath, "rb"); + if (fp == NULL) { + closesocket(sockfd); + return ERR_OPEN_FILE; + } + char sendbuf[1024]; + int nread, nsend; + int ntotal = 0; + while (1) { + nread = fread(sendbuf, 1, sizeof(sendbuf), fp); + if (nread == 0) break; + nsend = send(sockfd, sendbuf, nread, 0); + if (nsend != nread) break; + ntotal += nsend; + } + fclose(fp); + } + closesocket(sockfd); + nrecv = recv(hftp->sockfd, hftp->recvbuf, FTP_RECV_BUFSIZE, 0); + if (nrecv <= 0) { + closesocket(hftp->sockfd); + return ERR_RECV; + } + //printf("< %s", hftp->recvbuf); + status_code = atoi(hftp->recvbuf); + return status_code == FTP_STATUS_TRANSFER_COMPLETE ? 0 : status_code; +} + +static int s_ftp_download_cb(ftp_handle_t* hftp, char* buf, int len) { + FILE* fp = (FILE*)hftp->userdata; + if (fp == NULL) return -1; + if (len <= 0) { + fclose(fp); + hftp->userdata = NULL; + return 0; + } + return fwrite(buf, 1, len, fp); +} + +// remote => local +int ftp_download(ftp_handle_t* hftp, const char* remote_filepath, const char* local_filepath) { + FILE* fp = fopen(local_filepath, "wb"); + if (fp == NULL) { + return ERR_OPEN_FILE; + } + hftp->userdata = (void*)fp; + int ret = ftp_download_with_cb(hftp, remote_filepath, s_ftp_download_cb); + // ensure fclose + if (hftp->userdata != NULL) { + fclose(fp); + hftp->userdata = NULL; + } + return ret; +} diff --git a/external/libhv/libhv-1.3.2/protocol/ftp.h b/external/libhv/libhv-1.3.2/protocol/ftp.h new file mode 100644 index 0000000..d1b60ca --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/ftp.h @@ -0,0 +1,96 @@ +#ifndef HV_FTP_H_ +#define HV_FTP_H_ + +#include "hexport.h" + +#define FTP_COMMAND_PORT 21 +#define FTP_DATA_PORT 20 + +// ftp_command +// X(name) +#define FTP_COMMAND_MAP(X) \ + X(HELP) \ + X(USER) \ + X(PASS) \ + X(PWD) \ + X(CWD) \ + X(CDUP) \ + X(MKD) \ + X(RMD) \ + X(STAT) \ + X(SIZE) \ + X(DELE) \ + X(RNFR) \ + X(RNTO) \ + X(PORT) \ + X(PASV) \ + X(LIST) \ + X(NLST) \ + X(APPE) \ + X(RETR) \ + X(STOR) \ + X(QUIT) \ + +enum ftp_command { +#define X(name) FTP_##name, + FTP_COMMAND_MAP(X) +#undef X +}; + +// ftp_status +// XXX(code, name, string) +#define FTP_STATUS_MAP(XXX) \ + XXX(220, READY, Ready) \ + XXX(221, BYE, Bye) \ + XXX(226, TRANSFER_COMPLETE, Transfer complete) \ + XXX(227, PASV, Entering Passive Mode) \ + XXX(331, PASS, Password required) \ + XXX(230, LOGIN_OK, Login OK) \ + XXX(250, OK, OK) \ + XXX(500, BAD_SYNTAX, Bad syntax) \ + XXX(530, NOT_LOGIN, Not login) \ + +enum ftp_status { +#define XXX(code, name, string) FTP_STATUS_##name = code, + FTP_STATUS_MAP(XXX) +#undef XXX +}; + +// more friendly macros +#define FTP_MKDIR FTP_MKD +#define FTP_RMDIR FTP_RMD +#define FTP_APPEND FTP_APPE +#define FTP_REMOVE FTP_DELE +#define FTP_DOWNLOAD FTP_RETR +#define FTP_UPLOAD FTP_STOR + +#define FTP_RECV_BUFSIZE 8192 + +typedef struct ftp_handle_s { + int sockfd; + char recvbuf[FTP_RECV_BUFSIZE]; + void* userdata; +} ftp_handle_t; + +BEGIN_EXTERN_C + +HV_EXPORT const char* ftp_command_str(enum ftp_command cmd); +HV_EXPORT const char* ftp_status_str(enum ftp_status status); + +HV_EXPORT int ftp_connect(ftp_handle_t* hftp, const char* host, int port); +HV_EXPORT int ftp_login(ftp_handle_t* hftp, const char* username, const char* password); +HV_EXPORT int ftp_quit(ftp_handle_t* hftp); + +HV_EXPORT int ftp_exec(ftp_handle_t* hftp, const char* cmd, const char* param); + +// local => remote +HV_EXPORT int ftp_upload(ftp_handle_t* hftp, const char* local_filepath, const char* remote_filepath); +// remote => local +HV_EXPORT int ftp_download(ftp_handle_t* hftp, const char* remote_filepath, const char* local_filepath); + +typedef int (*ftp_download_cb)(ftp_handle_t* hftp, char* buf, int len); +HV_EXPORT int ftp_download_with_cb(ftp_handle_t* hftp, const char* filepath, ftp_download_cb cb); + +END_EXTERN_C + +#endif // HV_FTP_H_ diff --git a/external/libhv/libhv-1.3.2/protocol/icmp.c b/external/libhv/libhv-1.3.2/protocol/icmp.c new file mode 100644 index 0000000..864a839 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/icmp.c @@ -0,0 +1,125 @@ +#include "icmp.h" + +#include "netinet.h" +#include "hdef.h" +#include "hsocket.h" +#include "htime.h" + +#define PING_TIMEOUT 1000 // ms +int ping(const char* host, int cnt) { + static uint16_t seq = 0; + uint16_t pid16 = (uint16_t)getpid(); + char ip[64] = {0}; + uint32_t start_tick, end_tick; + uint64_t start_hrtime, end_hrtime; + int timeout = 0; + int sendbytes = 64; + char sendbuf[64]; + char recvbuf[128]; // iphdr + icmp = 84 at least + icmp_t* icmp_req = (icmp_t*)sendbuf; + iphdr_t* ipheader = (iphdr_t*)recvbuf; + icmp_t* icmp_res; + // ping stat + int send_cnt = 0; + int recv_cnt = 0; + int ok_cnt = 0; + float rtt, min_rtt, max_rtt, total_rtt; + rtt = max_rtt = total_rtt = 0.0f; + min_rtt = 1000000.0f; + //min_rtt = MIN(rtt, min_rtt); + //max_rtt = MAX(rtt, max_rtt); + // gethostbyname -> socket -> setsockopt -> sendto -> recvfrom -> closesocket + sockaddr_u peeraddr; + socklen_t addrlen = sizeof(peeraddr); + memset(&peeraddr, 0, addrlen); + int ret = ResolveAddr(host, &peeraddr); + if (ret != 0) return ret; + sockaddr_ip(&peeraddr, ip, sizeof(ip)); + int sockfd = socket(peeraddr.sa.sa_family, SOCK_RAW, IPPROTO_ICMP); + if (sockfd < 0) { + perror("socket"); + if (errno == EPERM) { + fprintf(stderr, "please use root or sudo to create a raw socket.\n"); + } + return -socket_errno(); + } + + timeout = PING_TIMEOUT; + ret = so_sndtimeo(sockfd, timeout); + if (ret < 0) { + perror("setsockopt"); + goto error; + } + timeout = PING_TIMEOUT; + ret = so_rcvtimeo(sockfd, timeout); + if (ret < 0) { + perror("setsockopt"); + goto error; + } + + icmp_req->icmp_type = ICMP_ECHO; + icmp_req->icmp_code = 0; + icmp_req->icmp_id = pid16; + for (int i = 0; i < sendbytes - sizeof(icmphdr_t); ++i) { + icmp_req->icmp_data[i] = i; + } + start_tick = gettick_ms(); + while (cnt-- > 0) { + // NOTE: checksum + icmp_req->icmp_seq = ++seq; + icmp_req->icmp_cksum = 0; + icmp_req->icmp_cksum = checksum((uint8_t*)icmp_req, sendbytes); + start_hrtime = gethrtime_us(); + addrlen = sockaddr_len(&peeraddr); + int nsend = sendto(sockfd, sendbuf, sendbytes, 0, &peeraddr.sa, addrlen); + if (nsend < 0) { + perror("sendto"); + continue; + } + ++send_cnt; + addrlen = sizeof(peeraddr); + int nrecv = recvfrom(sockfd, recvbuf, sizeof(recvbuf), 0, &peeraddr.sa, &addrlen); + if (nrecv < 0) { + perror("recvfrom"); + continue; + } + ++recv_cnt; + end_hrtime = gethrtime_us(); + // check valid + bool valid = false; + int iphdr_len = ipheader->ihl * 4; + int icmp_len = nrecv - iphdr_len; + if (icmp_len == sendbytes) { + icmp_res = (icmp_t*)(recvbuf + ipheader->ihl*4); + if (icmp_res->icmp_type == ICMP_ECHOREPLY && + icmp_res->icmp_id == pid16 && + icmp_res->icmp_seq == seq) { + valid = true; + } + } + if (valid == false) { + printd("recv invalid icmp packet!\n"); + continue; + } + rtt = (end_hrtime-start_hrtime) / 1000.0f; + min_rtt = MIN(rtt, min_rtt); + max_rtt = MAX(rtt, max_rtt); + total_rtt += rtt; + printd("%d bytes from %s: icmp_seq=%u ttl=%u time=%.1f ms\n", icmp_len, ip, seq, ipheader->ttl, rtt); + fflush(stdout); + ++ok_cnt; + if (cnt > 0) hv_sleep(1); // sleep a while, then agian + } + end_tick = gettick_ms(); + printd("--- %s ping statistics ---\n", host); + printd("%d packets transmitted, %d received, %d%% packet loss, time %d ms\n", + send_cnt, recv_cnt, (send_cnt-recv_cnt)*100/(send_cnt==0?1:send_cnt), end_tick-start_tick); + printd("rtt min/avg/max = %.3f/%.3f/%.3f ms\n", + min_rtt, total_rtt/(ok_cnt==0?1:ok_cnt), max_rtt); + + closesocket(sockfd); + return ok_cnt; +error: + closesocket(sockfd); + return socket_errno() > 0 ? -socket_errno() : -1; +} diff --git a/external/libhv/libhv-1.3.2/protocol/icmp.h b/external/libhv/libhv-1.3.2/protocol/icmp.h new file mode 100644 index 0000000..afd8349 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/icmp.h @@ -0,0 +1,15 @@ +#ifndef HV_ICMP_H_ +#define HV_ICMP_H_ + +#include "hexport.h" + +BEGIN_EXTERN_C + +// @param cnt: ping count +// @return: ok count +// @note: printd $CC -DPRINT_DEBUG +HV_EXPORT int ping(const char* host, int cnt DEFAULT(4)); + +END_EXTERN_C + +#endif // HV_ICMP_H_ diff --git a/external/libhv/libhv-1.3.2/protocol/smtp.c b/external/libhv/libhv-1.3.2/protocol/smtp.c new file mode 100644 index 0000000..d365559 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/smtp.c @@ -0,0 +1,256 @@ +#include "smtp.h" + +#include "hsocket.h" +#include "herr.h" +#include "base64.h" + +const char* smtp_command_str(enum smtp_command cmd) { + switch (cmd) { +#define XX(name, string) case SMTP_##name: return #string; + SMTP_COMMAND_MAP(XX) +#undef XX + default: return ""; + } +} + +const char* smtp_status_str(enum smtp_status status) { + switch (status) { +#define XXX(code, name, string) case SMTP_STATUS_##name: return #string; + SMTP_STATUS_MAP(XXX) +#undef XXX + default: return ""; + } +} + +int smtp_build_command(enum smtp_command cmd, const char* param, char* buf, int buflen) { + switch (cmd) { + // unary + case SMTP_DATA: + case SMTP_QUIT: + return snprintf(buf, buflen, "%s\r\n", smtp_command_str(cmd)); + //
+ case SMTP_MAIL: + case SMTP_RCPT: + return snprintf(buf, buflen, "%s <%s>\r\n", smtp_command_str(cmd), param); + default: + return snprintf(buf, buflen, "%s %s\r\n", smtp_command_str(cmd), param); + } +} + +// EHLO => AUTH PLAIN => MAIL => RCPT => DATA => data => EOB => QUIT +int sendmail(const char* smtp_server, + const char* username, + const char* password, + mail_t* mail) { + char buf[1024] = {0}; + int buflen = sizeof(buf); + int cmdlen = 0; + int status_code = 0; + char basic[256]; + int basiclen; + + int sockfd = ConnectTimeout(smtp_server, SMTP_PORT, DEFAULT_CONNECT_TIMEOUT); + if (sockfd < 0) { + return sockfd; + } + so_sndtimeo(sockfd, 5000); + so_rcvtimeo(sockfd, 5000); + + int ret, nsend, nrecv; + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_READY) { + ret = status_code; + goto error; + } + // EHLO smtp.xxx.com\r\n + cmdlen = smtp_build_command(SMTP_EHLO, smtp_server, buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_OK) { + ret = status_code; + goto error; + } + // AUTH PLAIN\r\n + cmdlen = smtp_build_command(SMTP_AUTH, "PLAIN", buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_AUTH) { + ret = status_code; + goto error; + } + { + // BASE64 \0username\0password + int usernamelen = strlen(username); + int passwordlen = strlen(password); + basic[0] = '\0'; + memcpy(basic+1, username, usernamelen); + basic[1+usernamelen] = '\0'; + memcpy(basic+1+usernamelen+1, password, passwordlen); + basiclen = 1 + usernamelen + 1 + passwordlen; + } + hv_base64_encode((unsigned char*)basic, basiclen, buf); + cmdlen = BASE64_ENCODE_OUT_SIZE(basiclen); + buf[cmdlen] = '\r'; + buf[cmdlen+1] = '\n'; + cmdlen += 2; + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_AUTH_SUCCESS) { + ret = status_code; + goto error; + } + // MAIL FROM: \r\n + cmdlen = smtp_build_command(SMTP_MAIL, mail->from, buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_OK) { + ret = status_code; + goto error; + } + // RCPT TO: \r\n + cmdlen = smtp_build_command(SMTP_RCPT, mail->to, buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_OK) { + ret = status_code; + goto error; + } + // DATA\r\n + cmdlen = smtp_build_command(SMTP_DATA, NULL, buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + status_code = atoi(buf); + // SMTP_STATUS_DATA + if (status_code >= 400) { + ret = status_code; + goto error; + } + // From: + cmdlen = snprintf(buf, buflen, "From:%s\r\n", mail->from); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + // To: + cmdlen = snprintf(buf, buflen, "To:%s\r\n", mail->to); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + // Subject: + cmdlen = snprintf(buf, buflen, "Subject:%s\r\n\r\n", mail->subject); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + // body + cmdlen = strlen(mail->body); + nsend = send(sockfd, mail->body, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + // EOB + nsend = send(sockfd, SMTP_EOB, SMTP_EOB_LEN, 0); + if (nsend != SMTP_EOB_LEN) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_SEND; + goto error; + } + status_code = atoi(buf); + if (status_code != SMTP_STATUS_OK) { + ret = status_code; + goto error; + } + // QUIT\r\n + cmdlen = smtp_build_command(SMTP_QUIT, NULL, buf, buflen); + nsend = send(sockfd, buf, cmdlen, 0); + if (nsend != cmdlen) { + ret = ERR_SEND; + goto error; + } + nrecv = recv(sockfd, buf, buflen, 0); + if (nrecv <= 0) { + ret = ERR_RECV; + goto error; + } + /* + status_code = atoi(buf); + if (status_code != SMTP_STATUS_BYE) { + ret = status_code; + goto error; + } + */ + ret = SMTP_STATUS_OK; + +error: + if (sockfd != INVALID_SOCKET) { + closesocket(sockfd); + } + return ret; +} diff --git a/external/libhv/libhv-1.3.2/protocol/smtp.h b/external/libhv/libhv-1.3.2/protocol/smtp.h new file mode 100644 index 0000000..ce00399 --- /dev/null +++ b/external/libhv/libhv-1.3.2/protocol/smtp.h @@ -0,0 +1,74 @@ +#ifndef HV_SMTP_H_ +#define HV_SMTP_H_ + +#include "hexport.h" + +#define SMTP_PORT 25 +#define SMTPS_PORT 465 +#define SMTP_EOB "\r\n.\r\n" +#define SMTP_EOB_LEN 5 + +// smtp_command +// XX(name, string) +#define SMTP_COMMAND_MAP(XX)\ + XX(HELO, HELO) \ + XX(EHLO, EHLO) \ + XX(AUTH, AUTH) \ + XX(MAIL, MAIL FROM:) \ + XX(RCPT, RCPT TO:) \ + XX(DATA, DATA) \ + XX(QUIT, QUIT) \ + +enum smtp_command { +#define XX(name, string) SMTP_##name, + SMTP_COMMAND_MAP(XX) +#undef XX +}; + +// smtp_status +// XXX(code, name, string) +#define SMTP_STATUS_MAP(XXX) \ + XXX(220, READY, Ready) \ + XXX(221, BYE, Bye) \ + XXX(235, AUTH_SUCCESS, Authentication success) \ + XXX(250, OK, OK) \ + XXX(334, AUTH, Auth input) \ + XXX(354, DATA, End with .) \ + XXX(500, BAD_SYNTAX, Bad syntax) \ + XXX(502, NOT_IMPLEMENTED,Command not implemented) \ + XXX(503, BAD_SEQUENCE, Bad sequence of commands) \ + XXX(504, UNRECOGNIZED_AUTH_TYPE, Unrecognized authentication type) \ + XXX(535, AUTH_FAILED, Authentication failed) \ + XXX(553, ERR_MAIL, Mailbox name not allowed) \ + XXX(554, ERR_DATA, Transaction failed) \ + +enum smtp_status { +#define XXX(code, name, string) SMTP_STATUS_##name = code, + SMTP_STATUS_MAP(XXX) +#undef XXX +}; + +typedef struct mail_s { + char* from; + char* to; + char* subject; + char* body; +} mail_t; + +BEGIN_EXTERN_C + +HV_EXPORT const char* smtp_command_str(enum smtp_command cmd); +HV_EXPORT const char* smtp_status_str(enum smtp_status status); + +// cmd param\r\n +HV_EXPORT int smtp_build_command(enum smtp_command cmd, const char* param, char* buf, int buflen); +// status_code status_message\r\n + +HV_EXPORT int sendmail(const char* smtp_server, + const char* username, + const char* password, + mail_t* mail); + +END_EXTERN_C + +#endif // HV_SMTP_H_ diff --git a/external/libhv/libhv-1.3.2/scripts/check.sh b/external/libhv/libhv-1.3.2/scripts/check.sh new file mode 100755 index 0000000..dfe9171 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/check.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. +cd ${ROOT_DIR} + +bin/httpd -c etc/httpd.conf -s restart -d +ps aux | grep httpd +HTTPS=`netstat -atn | grep 8443 | wc -l` + +bin/http_client_test +bin/curl -v http://127.0.0.1:8080/ +if [ $HTTPS -gt 0 ]; then + bin/curl -v https://127.0.0.1:8443/ +fi +bin/wrk -c 100 -t 2 -d 10s http://127.0.0.1:8080/ping diff --git a/external/libhv/libhv-1.3.2/scripts/cmake_cross_compile.sh b/external/libhv/libhv-1.3.2/scripts/cmake_cross_compile.sh new file mode 100755 index 0000000..3a5ce06 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/cmake_cross_compile.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. + +if [ $# -gt 0 ]; then +CROSS_COMPILE=$1 +else +sudo apt install g++-arm-linux-gnueabi +CROSS_COMPILE=arm-linux-gnueabi- +fi +echo CROSS_COMPILE=${CROSS_COMPILE} + +cd ${ROOT_DIR} +. scripts/toolchain.sh export ${CROSS_COMPILE} +BUILD_DIR=build/${HV_TARGET_OS}/${HV_TARGET_ARCH} +echo BUILD_DIR=${BUILD_DIR} +mkdir -p ${BUILD_DIR} +cd ${BUILD_DIR} +cmake ../../.. -DCMAKE_C_COMPILER=$CC -DCMAKE_CXX_COMPILER=$CXX -DCMAKE_SYSTEM_NAME=$HV_TARGET_OS -DCMAKE_SYSTEM_PROCESSOR=$HV_TARGET_ARCH +make libhv libhv_static +cd ${ROOT_DIR} +. scripts/toolchain.sh unset ${CROSS_COMPILE} + +echo 'Completed => ${BUILD_DIR}' diff --git a/external/libhv/libhv-1.3.2/scripts/consul.py b/external/libhv/libhv-1.3.2/scripts/consul.py new file mode 100755 index 0000000..a9fe7e1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/consul.py @@ -0,0 +1,89 @@ +#!/usr/bin/python3 + +import sys +import json +import requests + +headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', + 'Cache-Control': 'no-cache', + 'Accpet': '*/*', + 'Content-Type': 'application/json'} + +_node = {'ip': '127.0.0.1', 'port': 8500} + +def gen_ServiceID(service_name, service_ip, service_port): + return service_name + '-' + service_ip + ':' + str(service_port) + +def register_service(service_name, service_ip, service_port , node=_node): + service = {} + service['Name'] = service_name + service['Address'] = service_ip + service['Port'] = service_port + service['ID'] = gen_ServiceID(service_name, service_ip, service_port) + check = {} + check['TCP'] = service['Address'] + ':' + str(service['Port']) + check['Interval'] = '10s' + check['DeregisterCriticalServiceAfter'] = '30s' + service['Check'] = check + data = json.dumps(service) + url = 'http://' + node['ip'] + ':' + str(node['port']) + url += '/v1/agent/service/register' + try: + res = requests.put(url=url, headers=headers, data=data) + return res.status_code == 200 and len(res.content) == 0 + except Exception as e: + print(e) + return False + +def deregister_service(ServiceID, node=_node): + url = 'http://' + node['ip'] + ':' + str(node['port']) + url += '/v1/agent/service/deregister/' + url += ServiceID + try: + res = requests.put(url=url, headers=headers) + return res.status_code == 200 and len(res.content) == 0 + except Exception as e: + print(e) + return False + +def discover_service(service_name, node=_node): + url = 'http://' + node['ip'] + ':' + str(node['port']) + url += '/v1/catalog/service/' + url += service_name + try: + res = requests.get(url=url, headers=headers) + return res.content + except Exception as e: + print(e) + return 'false' + +def main(): + print(sys.argv) + if len(sys.argv) < 4: + print('Usage: cmd service_name service_ip service_port node_ip node_port') + return + service_name = sys.argv[1] + service_ip = sys.argv[2] + service_port = int(sys.argv[3]) + if len(sys.argv) >= 5: + _node['ip'] = sys.argv[4] + _node['port'] = int(sys.argv[5]) + ServiceID = gen_ServiceID(service_name, service_ip, service_port) + if register_service(service_name, service_ip, service_port): + print('register_service [%s] succeed!' % (ServiceID)) + else: + print('register_service failed!') + + print(discover_service(service_name)) + + ''' + if deregister_service(ServiceID): + print('deregister_service [%s] succeed!' % (ServiceID)) + else: + print('deregister_service failed') + + print(discover_service(service_name)) + ''' + +if __name__ == '__main__': + main() diff --git a/external/libhv/libhv-1.3.2/scripts/consul_agent.sh b/external/libhv/libhv-1.3.2/scripts/consul_agent.sh new file mode 100755 index 0000000..0e15897 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/consul_agent.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +rm -r consul +rm nohup.out +mkdir consul + +print_help() { +cat < /proc/sys/kernel/core_uses_pid +echo "/tmp/core-%e-%p-%t" > /proc/sys/kernel/core_pattern +echo "1" > /proc/sys/fs/suid_dumpable +print_conf + +ulimit -c unlimited +ulimit -a diff --git a/external/libhv/libhv-1.3.2/scripts/create_repo.sh b/external/libhv/libhv-1.3.2/scripts/create_repo.sh new file mode 100755 index 0000000..a9fa0b6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/create_repo.sh @@ -0,0 +1,13 @@ +#!/bin/bash + +mkdir -p include lib src bin doc etc 3rd/include 3rd/lib dist +touch README.md BUILD.md RELEASE.md CHANGELOG.md Makefile .gitignore +git init + +# personal +git submodule add https://github.com/ithewei/libhv.git src/hv +cp src/hv/.gitignore . +cp src/hv/.clang-format . +cp src/hv/Makefile . +cp -r src/hv/etc/* etc +cp src/hv/examples/hmain_test.cpp src/main.cpp diff --git a/external/libhv/libhv-1.3.2/scripts/libhv.cmake b/external/libhv/libhv-1.3.2/scripts/libhv.cmake new file mode 100644 index 0000000..916c37e --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/libhv.cmake @@ -0,0 +1,9 @@ +set(CMAKE_C_COMPILER $CC) +set(CMAKE_CXX_COMPILER $CXX) + +set(CMAKE_SYSTEM_NAME $HV_TARGET_OS) +set(CMAKE_SYSTEM_PROCESSOR $HV_TARGET_ARCH) + +if(WIN32) + add_definitions(-D_WIN32_WINNT=0x600) +endif() diff --git a/external/libhv/libhv-1.3.2/scripts/shini.sh b/external/libhv/libhv-1.3.2/scripts/shini.sh new file mode 100644 index 0000000..266ae95 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/shini.sh @@ -0,0 +1,311 @@ +# shini - compatible INI library for sh +# +# This code is released freely under the MIT license - see the shipped LICENSE document. +# For the latest version etc, please see https://github.com/wallyhall/shini +# + +# Solely for the purpose of portable performance, this script breaks good practice to +# avoid forking subshells. One such good practice is avoiding global variables. +# This variable is used to carry non-numeric results from functions to the caller. +# Alternatively an echo and "$(...)" approach could be used, but is significantly slower. + +shini_setup() +{ + if [ -n "$ZSH_VERSION" ]; then + RESTORE_OPTS=$(set +o) + # Enable BASH_REMATCH for zsh + setopt KSH_ARRAYS BASH_REMATCH + fi +} + +shini_teardown() +{ + [ -n "$ZSH_VERSION" ] && eval "$RESTORE_OPTS" +} + +shini_function_exists() +{ + type "$1" > /dev/null 2>&1 + return $? +} + +shini_regex_match() +{ + # $KSH_VERSION (I'm told) only exists on ksh 93 and above, which supports regex matching. + if [ -n "$BASH_VERSINFO" ] && [ "$BASH_VERSINFO" -ge 3 ] || \ + [ -n "$ZSH_VERSION" ] || \ + [ -n "$KSH_VERSION" ]; then + [[ "$1" =~ $2 ]] && return 0 || return 1 + fi + + printf '%s' "$1" | grep -qe "$2" + return $? +} + +shini_regex_replace() +{ + if [ -n "$BASH_VERSINFO" ] && [ "${BASH_VERSINFO}" -ge 3 ] || \ + [ -n "$ZSH_VERSION" ]; then + [[ "$1" =~ $2 ]] && shini_retval=${BASH_REMATCH[1]} || shini_retval="$1" + return 0 + fi + + shini_retval="$(printf '%s' "$1" | sed -E "s/$2/\1/")" # If you have isses on older systems, + # it may be the non-newer POSIX compliant sed. + # -E should be enabling extended regex mode portably. +} + +# @param inifile Filename of INI file to parse +# @param postfix Function postfix for callbacks (optional) +# @param extra Extra argument for callbacks (optional) +shini_parse() +{ + shini_parse_section "$1" '' "$2" "$3" "$4" "$5" +} + +# @param inifile Filename of INI file to parse +# @param section Section to parse (or empty string for entire file) +# @param postfix Function postfix for callbacks (optional) +# @param extra Extra argument for callbacks (optional) +shini_parse_section() +{ + shini_setup + # ******** + + RX_KEY='[a-zA-Z0-9_\-\.]' + RX_VALUE="[^;\"]" + RX_SECTION='[a-zA-Z0-9_\-]' + RX_WS='[ ]' + RX_QUOTE='"' + RX_HEX='[0-9A-F]' + POSTFIX='' + SKIP_TO_SECTION='' + EXTRA1='' + EXTRA2='' + EXTRA3='' + SECTION_FOUND=-1 + + if [ $# -ge 2 ] && [ ! -z "$2" ]; then + SKIP_TO_SECTION="$2" + fi + + if [ $# -ge 3 ] && [ ! -z "$3" ]; then + POSTFIX="_$3" + fi + + if [ $# -ge 4 ] && ! [ -z "$4" ]; then + EXTRA1="$4" + fi + + if [ $# -ge 5 ] && [ ! -z "$5" ]; then + EXTRA2="$5" + fi + + if [ $# -ge 6 ] && [ ! -z "$6" ]; then + EXTRA3="$6" + fi + + if ! shini_function_exists "__shini_parsed${POSTFIX}"; then + printf 'shini: __shini_parsed%s function not declared.\n' "${POSTFIX}" 1>&2 + exit 255 + fi + + if [ $# -lt 1 ]; then + if shini_function_exists "__shini_no_file_passed{$POSTFIX}"; then + "__shini_no_file_passed${POSTFIX}" "$EXTRA1" "$EXTRA2" "$EXTRA3" + else + printf 'shini: Argument 1 needs to specify the INI file to parse.\n' 1>&2 + exit 254 + fi + fi + INI_FILE="$1" + + if [ ! -r "$INI_FILE" ]; then + if shini_function_exists "__shini_file_unreadable${POSTFIX}"; then + "__shini_file_unreadable${POSTFIX}" "$INI_FILE" "$EXTRA1" "$EXTRA2" "$EXTRA3" + else + printf 'shini: Unable to read INI file:\n `%s`\n' "$INI_FILE" 1>&2 + exit 253 + fi + fi + + # Iterate INI file line by line + LINE_NUM=0 + SECTION='' + while read LINE || [ -n "$LINE" ]; do # -n $LINE catches final line if not empty + # Check for new sections + if shini_regex_match "$LINE" "^${RX_WS}*\[${RX_SECTION}${RX_SECTION}*\]${RX_WS}*$"; then + shini_regex_replace "$LINE" "^${RX_WS}*\[(${RX_SECTION}${RX_SECTION}*)\]${RX_WS}*$" "\1" + SECTION=$shini_retval + + if [ "$SKIP_TO_SECTION" != '' ]; then + # stop once specific section is finished + [ $SECTION_FOUND -eq 0 ] && break; + + # mark the specified section as found + [ "$SKIP_TO_SECTION" = "$SECTION" ] && SECTION_FOUND=0; + fi + + if shini_function_exists "__shini_parsed_section${POSTFIX}"; then + "__shini_parsed_section${POSTFIX}" "$SECTION" "$EXTRA1" "$EXTRA2" "$EXTRA3" + fi + + LINE_NUM=$((LINE_NUM+1)) + continue + fi + + # Skip over sections we don't care about, if a specific section was specified + [ "$SKIP_TO_SECTION" != '' ] && [ $SECTION_FOUND -ne 0 ] && LINE_NUM=$((LINE_NUM+1)) && continue; + + # Check for new values + if shini_regex_match "$LINE" "^${RX_WS}*${RX_KEY}${RX_KEY}*${RX_WS}*="; then + shini_regex_replace "$LINE" "^${RX_WS}*(${RX_KEY}${RX_KEY}*)${RX_WS}*=.*$" + KEY=$shini_retval + + shini_regex_replace "$LINE" "^${RX_WS}*${RX_KEY}${RX_KEY}*${RX_WS}*=${RX_WS}*${RX_QUOTE}{0,1}(${RX_VALUE}*)${RX_QUOTE}{0,1}(${RX_WS}*\;.*)*$" + VALUE=$shini_retval + + if shini_regex_match "$LINE" "^0x${RX_HEX}${RX_HEX}*$"; then + VALUE=$(printf '%d' "$VALUE") + fi + + "__shini_parsed${POSTFIX}" "$SECTION" "$KEY" "$VALUE" "$EXTRA1" "$EXTRA2" "$EXTRA3" + + if shini_function_exists "__shini_parsed_comment${POSTFIX}"; then + if shini_regex_match "$LINE" ";"; then + shini_regex_replace "$LINE" "^.*\;(.*)$" + COMMENT=$shini_retval + + "__shini_parsed_comment${POSTFIX}" "$COMMENT" "$EXTRA1" "$EXTRA2" "$EXTRA3" + fi + fi + + LINE_NUM=$((LINE_NUM+1)) + continue + fi + + # Announce parse errors + if [ "$LINE" != '' ] && + ! shini_regex_match "$LINE" "^${RX_WS}*;.*$" && + ! shini_regex_match "$LINE" "^${RX_WS}*$"; then + if shini_function_exists "__shini_parse_error${POSTFIX}"; then + "__shini_parse_error${POSTFIX}" $LINE_NUM "$LINE" "$EXTRA1" "$EXTRA2" "$EXTRA3" + else + printf 'shini: Unable to parse line %d:\n `%s`\n' $LINE_NUM "$LINE" + fi + fi + + LINE_NUM=$((LINE_NUM+1)) + done < "$INI_FILE" + + # ******** + shini_teardown +} + +# @param inifile Filename of INI file to write to +# @param section Section of INI file to write to +# @param variable Variable name to add/update/delete +# @param value Value to add/update, do not specify to delete +shini_write() +{ + shini_setup + # ******** + + # This is not yet optimised (early write support only) - + # We actually re-parse the entire file, looking for the location in which to + # write the new value, writing out everything we parse as-is meanwhile. + + # Declare the following if you want particular behaviour (like skipping + # broken INI file content or handling an unreadable file etc). + # __shini_no_file_passed__writer() + # __shini_file_unreadable__writer() + # __shini_parse_error__writer() + + # Writer callbacks, used for writing the INI file content + __shini_parsed_section__writer() + { + # Validate the last section wasn't the target section + if [ "$LAST_SECTION" = "$WRITE_SECTION" ]; then + # If it was, and the value wasn't written already, write it + if [ $VALUE_WRITTEN -eq 0 ]; then + printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" + VALUE_WRITTEN=1 + fi + fi + printf "\n[%s]" "$1" >> "$INI_FILE_TEMP" + + LAST_SECTION="$1" + } + + __shini_parsed_comment__writer() + { + printf ";%s" "$1" >> "$INI_FILE_TEMP" + } + + __shini_parsed__writer() + { + if [ "$1" = "$WRITE_SECTION" ]; then + if [ "$2" = "$WRITE_KEY" ]; then + if [ ! -z "$WRITE_VALUE" ]; then + printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" + fi + VALUE_WRITTEN=1 + return + fi + fi + + printf "\n%s=%s" "$2" "$3" >> "$INI_FILE_TEMP" + } + + if [ $# -lt 3 ]; then + if shini_function_exists "__shini_no_file_passed"; then + __shini_no_file_passed + else + printf 'shini: Argument 1 needs to specify the INI file to write.\n' 1>&2 + exit 254 + fi + fi + + INI_FILE="$1" + INI_FILE_TEMP="$(mktemp -t shini_XXXXXX)" + + WRITE_SECTION="$2" + WRITE_KEY="$3" + WRITE_VALUE="$4" + LAST_SECTION="" + VALUE_WRITTEN=0 + + shini_parse "$1" "_writer" "$2" "$3" "$4" + # Still not written out yet + if [ $VALUE_WRITTEN -eq 0 ]; then + # Check if final existing section was target one, add it if not + if [ "$LAST_SECTION" != "$WRITE_SECTION" ]; then + printf "\n[%s]" "$WRITE_SECTION" >> "$INI_FILE_TEMP" + fi + # Write value at end of file + printf "\n%s=%s" "$WRITE_KEY" "$WRITE_VALUE" >> "$INI_FILE_TEMP" + fi + + mv "$INI_FILE_TEMP" "$INI_FILE" + + # ******** + shini_teardown +} + +# default usage +__shini_parsed() +{ + if [[ $2 != *\$* ]] && [[ $3 != *\$* ]]; then + eval $2=$3 + fi +} + +__shini_parse_error() +{ + error_line=$1 +} + +__shini_parse_error__writer() +{ + error_line=$1 +} diff --git a/external/libhv/libhv-1.3.2/scripts/test-coverage.sh b/external/libhv/libhv-1.3.2/scripts/test-coverage.sh new file mode 100755 index 0000000..6f9d7ba --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/test-coverage.sh @@ -0,0 +1,40 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. +cd ${ROOT_DIR} + +bin/httpd -c etc/httpd.conf -s restart -d + +bin/ls +bin/date +bin/ifconfig +bin/mkdir_p 123/456 +bin/rmdir_p 123/456 + +bin/defer_test +bin/hstring_test +bin/hpath_test +bin/hatomic_test +bin/hatomic_cpp_test +bin/hmutex_test +bin/socketpair_test +bin/threadpool_test +bin/objectpool_test + +bin/curl -v localhost:8080 +bin/curl -v localhost:8080/ping +bin/curl -v localhost:8080/echo -d "hello,world!" +bin/curl -v localhost:8080/query?page_no=1\&page_size=10 +bin/curl -v localhost:8080/kv -H "Content-Type:application/x-www-form-urlencoded" -d 'user=admin&pswd=123456' +bin/curl -v localhost:8080/json -H "Content-Type:application/json" -d '{"user":"admin","pswd":"123456"}' +bin/curl -v localhost:8080/form -F "user=admin pswd=123456" +bin/curl -v localhost:8080/upload -F "file=@LICENSE" +bin/curl -v localhost:8080/test -H "Content-Type:application/x-www-form-urlencoded" -d 'bool=1&int=123&float=3.14&string=hello' +bin/curl -v localhost:8080/test -H "Content-Type:application/json" -d '{"bool":true,"int":123,"float":3.14,"string":"hello"}' +bin/curl -v localhost:8080/test -F 'bool=1 int=123 float=3.14 string=hello' +bin/curl -v -X DELETE localhost:8080/group/test/user/123 + +bin/httpd -s stop + +bin/htimer_test diff --git a/external/libhv/libhv-1.3.2/scripts/toolchain.sh b/external/libhv/libhv-1.3.2/scripts/toolchain.sh new file mode 100755 index 0000000..31565bb --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/toolchain.sh @@ -0,0 +1,101 @@ +#!/bin/bash + +print_help() { +cat <&1 | grep Target | sed 's/Target: //'` + TARGET_ARCH=`echo $TARGET_PLATFORM | awk -F'-' '{print $1}'` + + case $TARGET_PLATFORM in + *mingw*) TARGET_OS=Windows ;; + *android*) TARGET_OS=Android ;; + *darwin*) TARGET_OS=Darwin ;; + *) TARGET_OS=Linux ;; + esac + # TARGET_OS,TARGET_ARCH used by make + export HV_HOST_OS=$HOST_OS + export HV_HOST_ARCH=$HOST_ARCH + export HV_TARGET_OS=$TARGET_OS + export HV_TARGET_ARCH=$TARGET_ARCH + export HOST=$TARGET_PLATFORM + elif [ $COMMAND = "unset" ]; then + unset CROSS_COMPILE + unset CC + unset CXX + unset AR + unset AS + unset LD + unset STRIP + unset RANLIB + unset NM + + unset HOST_OS + unset HOST_ARCH + unset TARGET_OS + unset TARGET_ARCH + unset HOST + else + print_help + return + fi +} + +main $@ +echo "CC = $CC" +echo "CXX = $CXX" +if [ $CC ]; then +CC_VERSION=`$CC --version 2>&1 | head -n 1` +echo "$CC_VERSION" +fi +echo "AR = $AR" +echo "AS = $AS" +echo "LD = $LD" +echo "STRIP = $STRIP" +echo "RANLIB = $RANLIB" +echo "NM = $NM" + +echo "HV_HOST_OS = $HOST_OS" +echo "HV_HOST_ARCH = $HOST_ARCH" +echo "HV_TARGET_OS = $TARGET_OS" +echo "HV_TARGET_ARCH = $TARGET_ARCH" diff --git a/external/libhv/libhv-1.3.2/scripts/unittest.sh b/external/libhv/libhv-1.3.2/scripts/unittest.sh new file mode 100755 index 0000000..8d6de66 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/unittest.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +SCRIPT_DIR=$(cd `dirname $0`; pwd) +ROOT_DIR=${SCRIPT_DIR}/.. +cd ${ROOT_DIR} + +bin/rbtree_test +bin/hbase_test +bin/date +bin/ifconfig +bin/mkdir_p 123/456 +bin/ls +bin/rmdir_p 123/456 + +bin/base64 +bin/md5 +bin/sha1 + +bin/defer_test +bin/hstring_test +bin/hpath_test +bin/hurl_test +# bin/hatomic_test +# bin/hatomic_cpp_test +# bin/hthread_test +# bin/hmutex_test +bin/socketpair_test +# bin/threadpool_test +# bin/objectpool_test +bin/sizeof_test diff --git a/external/libhv/libhv-1.3.2/scripts/websocket_server.py b/external/libhv/libhv-1.3.2/scripts/websocket_server.py new file mode 100755 index 0000000..f300d07 --- /dev/null +++ b/external/libhv/libhv-1.3.2/scripts/websocket_server.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 + +# pip3 install websockets + +import asyncio +import websockets + +async def echo(websocket): + async for message in websocket: + print(message) + await websocket.send(message) + +async def serve(port): + async with websockets.serve(echo, "0.0.0.0", port): + await asyncio.Future() + +if __name__ == "__main__": + asyncio.run(serve(9999)) diff --git a/external/libhv/libhv-1.3.2/ssl/appletls.c b/external/libhv/libhv-1.3.2/ssl/appletls.c new file mode 100644 index 0000000..a74fee1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/appletls.c @@ -0,0 +1,1114 @@ +#include "hssl.h" + +#ifdef WITH_APPLETLS + +/* Disclaimer: excerpted from curl */ + +#include +/* For some reason, when building for iOS, the omnibus header above does + * not include SecureTransport.h as of iOS SDK 5.1. */ +#include +#include +#include + +#include "hsocket.h" + +/* The Security framework has changed greatly between iOS and different macOS + versions, and we will try to support as many of them as we can (back to + Leopard and iOS 5) by using macros and weak-linking. + In general, you want to build this using the most recent OS SDK, since some + features require curl to be built against the latest SDK. TLS 1.1 and 1.2 + support, for instance, require the macOS 10.8 SDK or later. TLS 1.3 + requires the macOS 10.13 or iOS 11 SDK or later. */ +#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) + +#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050 +#error "The Secure Transport back-end requires Leopard or later." +#endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */ + +#define CURL_BUILD_IOS 0 +#define CURL_BUILD_IOS_7 0 +#define CURL_BUILD_IOS_9 0 +#define CURL_BUILD_IOS_11 0 +#define CURL_BUILD_IOS_13 0 +#define CURL_BUILD_MAC 1 +/* This is the maximum API level we are allowed to use when building: */ +#define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050 +#define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 +#define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 +#define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080 +#define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090 +#define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100 +#define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300 +#define CURL_BUILD_MAC_10_15 MAC_OS_X_VERSION_MAX_ALLOWED >= 101500 +/* These macros mean "the following code is present to allow runtime backward + compatibility with at least this cat or earlier": + (You set this at build-time using the compiler command line option + "-mmacosx-version-min.") */ +#define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050 +#define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060 +#define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070 +#define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080 +#define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090 + +#elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE +#define CURL_BUILD_IOS 1 +#define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000 +#define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000 +#define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 +#define CURL_BUILD_IOS_13 __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 +#define CURL_BUILD_MAC 0 +#define CURL_BUILD_MAC_10_5 0 +#define CURL_BUILD_MAC_10_6 0 +#define CURL_BUILD_MAC_10_7 0 +#define CURL_BUILD_MAC_10_8 0 +#define CURL_BUILD_MAC_10_9 0 +#define CURL_BUILD_MAC_10_11 0 +#define CURL_BUILD_MAC_10_13 0 +#define CURL_BUILD_MAC_10_15 0 +#define CURL_SUPPORT_MAC_10_5 0 +#define CURL_SUPPORT_MAC_10_6 0 +#define CURL_SUPPORT_MAC_10_7 0 +#define CURL_SUPPORT_MAC_10_8 0 +#define CURL_SUPPORT_MAC_10_9 0 + +#else +#error "The Secure Transport back-end requires iOS or macOS." +#endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */ + +#if !defined(__MAC_10_8) +static const SSLProtocol kTLSProtocol11 = (SSLProtocol)7; +static const SSLProtocol kTLSProtocol12 = (SSLProtocol)8; +#endif + +#if !defined(__MAC_10_13) +static const SSLProtocol kTLSProtocol13 = (SSLProtocol)10; +#endif + +static inline const char* SSLProtocolToString(SSLProtocol proto) { + switch(proto) { + case kSSLProtocol2: return "SSLv2"; + case kSSLProtocol3: return "SSLv3"; + case kTLSProtocol1: return "TLSv1"; + case kTLSProtocol11: return "TLSv1.1"; + case kTLSProtocol12: return "TLSv1.2"; + case kTLSProtocol13: return "TLSv1.3"; + default: return "Unknown"; + } +} + +struct st_cipher { + const char *name; /* Cipher suite IANA name. It starts with "TLS_" prefix */ + const char *alias_name; /* Alias name is the same as OpenSSL cipher name */ + SSLCipherSuite num; /* Cipher suite code/number defined in IANA registry */ + bool weak; /* Flag to mark cipher as weak based on previous implementation + of Secure Transport back-end by CURL */ +}; + +/* Macro to initialize st_cipher data structure: stringify id to name, cipher + number/id, 'weak' suite flag + */ +#define CIPHER_DEF(num, alias, weak) \ + { #num, alias, num, weak } + +/* + Macro to initialize st_cipher data structure with name, code (IANA cipher + number/id value), and 'weak' suite flag. The first 28 cipher suite numbers + have the same IANA code for both SSL and TLS standards: numbers 0x0000 to + 0x001B. They have different names though. The first 4 letters of the cipher + suite name are the protocol name: "SSL_" or "TLS_", rest of the IANA name is + the same for both SSL and TLS cipher suite name. + The second part of the problem is that macOS/iOS SDKs don't define all TLS + codes but only 12 of them. The SDK defines all SSL codes though, i.e. SSL_NUM + constant is always defined for those 28 ciphers while TLS_NUM is defined only + for 12 of the first 28 ciphers. Those 12 TLS cipher codes match to + corresponding SSL enum value and represent the same cipher suite. Therefore + we'll use the SSL enum value for those cipher suites because it is defined + for all 28 of them. + We make internal data consistent and based on TLS names, i.e. all st_cipher + item names start with the "TLS_" prefix. + Summarizing all the above, those 28 first ciphers are presented in our table + with both TLS and SSL names. Their cipher numbers are assigned based on the + SDK enum value for the SSL cipher, which matches to IANA TLS number. + */ +#define CIPHER_DEF_SSLTLS(num_wo_prefix, alias, weak) \ + { "TLS_" #num_wo_prefix, alias, SSL_##num_wo_prefix, weak } + +/* + Cipher suites were marked as weak based on the following: + RC4 encryption - rfc7465, the document contains a list of deprecated ciphers. + Marked in the code below as weak. + RC2 encryption - many mentions, was found vulnerable to a relatively easy + attack https://link.springer.com/chapter/10.1007%2F3-540-69710-1_14 + Marked in the code below as weak. + DES and IDEA encryption - rfc5469, has a list of deprecated ciphers. + Marked in the code below as weak. + Anonymous Diffie-Hellman authentication and anonymous elliptic curve + Diffie-Hellman - vulnerable to a man-in-the-middle attack. Deprecated by + RFC 4346 aka TLS 1.1 (section A.5, page 60) + Null bulk encryption suites - not encrypted communication + Export ciphers, i.e. ciphers with restrictions to be used outside the US for + software exported to some countries, they were excluded from TLS 1.1 + version. More precisely, they were noted as ciphers which MUST NOT be + negotiated in RFC 4346 aka TLS 1.1 (section A.5, pages 60 and 61). + All of those filters were considered weak because they contain a weak + algorithm like DES, RC2 or RC4, and already considered weak by other + criteria. + 3DES - NIST deprecated it and is going to retire it by 2023 + https://csrc.nist.gov/News/2017/Update-to-Current-Use-and-Deprecation-of-TDEA + OpenSSL https://www.openssl.org/blog/blog/2016/08/24/sweet32/ also + deprecated those ciphers. Some other libraries also consider it + vulnerable or at least not strong enough. + CBC ciphers are vulnerable with SSL3.0 and TLS1.0: + https://www.cisco.com/c/en/us/support/docs/security/email-security-appliance + /118518-technote-esa-00.html + We don't take care of this issue because it is resolved by later TLS + versions and for us, it requires more complicated checks, we need to + check a protocol version also. Vulnerability doesn't look very critical + and we do not filter out those cipher suites. + */ + +#define CIPHER_WEAK_NOT_ENCRYPTED TRUE +#define CIPHER_WEAK_RC_ENCRYPTION TRUE +#define CIPHER_WEAK_DES_ENCRYPTION TRUE +#define CIPHER_WEAK_IDEA_ENCRYPTION TRUE +#define CIPHER_WEAK_ANON_AUTH TRUE +#define CIPHER_WEAK_3DES_ENCRYPTION TRUE +#define CIPHER_STRONG_ENOUGH FALSE + +/* Please do not change the order of the first ciphers available for SSL. + Do not insert and do not delete any of them. Code below + depends on their order and continuity. + If you add a new cipher, please maintain order by number, i.e. + insert in between existing items to appropriate place based on + cipher suite IANA number +*/ +const static struct st_cipher ciphertable[] = { + /* SSL version 3.0 and initial TLS 1.0 cipher suites. + Defined since SDK 10.2.8 */ + CIPHER_DEF_SSLTLS(NULL_WITH_NULL_NULL, /* 0x0000 */ + NULL, + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_WITH_NULL_MD5, /* 0x0001 */ + "NULL-MD5", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_WITH_NULL_SHA, /* 0x0002 */ + "NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC4_40_MD5, /* 0x0003 */ + "EXP-RC4-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_MD5, /* 0x0004 */ + "RC4-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_RC4_128_SHA, /* 0x0005 */ + "RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_RC2_CBC_40_MD5, /* 0x0006 */ + "EXP-RC2-CBC-MD5", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_IDEA_CBC_SHA, /* 0x0007 */ + "IDEA-CBC-SHA", + CIPHER_WEAK_IDEA_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0008 */ + "EXP-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_DES_CBC_SHA, /* 0x0009 */ + "DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */ + "DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x000B */ + "EXP-DH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_WITH_DES_CBC_SHA, /* 0x000C */ + "DH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x000D */ + "DH-DSS-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x000E */ + "EXP-DH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_WITH_DES_CBC_SHA, /* 0x000F */ + "DH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0010 */ + "DH-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, /* 0x0011 */ + "EXP-EDH-DSS-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_WITH_DES_CBC_SHA, /* 0x0012 */ + "EDH-DSS-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_DSS_WITH_3DES_EDE_CBC_SHA, /* 0x0013 */ + "DHE-DSS-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, /* 0x0014 */ + "EXP-EDH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_WITH_DES_CBC_SHA, /* 0x0015 */ + "EDH-RSA-DES-CBC-SHA", + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x0016 */ + "DHE-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_RC4_40_MD5, /* 0x0017 */ + "EXP-ADH-RC4-MD5", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_RC4_128_MD5, /* 0x0018 */ + "ADH-RC4-MD5", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_EXPORT_WITH_DES40_CBC_SHA, /* 0x0019 */ + "EXP-ADH-DES-CBC-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_DES_CBC_SHA, /* 0x001A */ + "ADH-DES-CBC-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF_SSLTLS(DH_anon_WITH_3DES_EDE_CBC_SHA, /* 0x001B */ + "ADH-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_NULL_SHA, /* 0x001C */ + NULL, + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, /* 0x001D */ + NULL, + CIPHER_STRONG_ENOUGH), + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* RFC 4785 - Pre-Shared Key (PSK) Ciphersuites with NULL Encryption */ + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA, /* 0x002C */ + "PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA, /* 0x002D */ + "DHE-PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA, /* 0x002E */ + "RSA-PSK-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + + /* TLS addenda using AES, per RFC 3268. Defined since SDK 10.4u */ + CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */ + "AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA, /* 0x0030 */ + "DH-DSS-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA, /* 0x0031 */ + "DH-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA, /* 0x0032 */ + "DHE-DSS-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA, /* 0x0033 */ + "DHE-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA, /* 0x0034 */ + "ADH-AES128-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */ + "AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA, /* 0x0036 */ + "DH-DSS-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA, /* 0x0037 */ + "DH-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA, /* 0x0038 */ + "DHE-DSS-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA, /* 0x0039 */ + "DHE-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA, /* 0x003A */ + "ADH-AES256-SHA", + CIPHER_WEAK_ANON_AUTH), + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* TLS 1.2 addenda, RFC 5246 */ + /* Server provided RSA certificate for key exchange. */ + CIPHER_DEF(TLS_RSA_WITH_NULL_SHA256, /* 0x003B */ + "NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */ + "AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */ + "AES256-SHA256", + CIPHER_STRONG_ENOUGH), + /* Server-authenticated (and optionally client-authenticated) + Diffie-Hellman. */ + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_CBC_SHA256, /* 0x003E */ + "DH-DSS-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_CBC_SHA256, /* 0x003F */ + "DH-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256, /* 0x0040 */ + "DHE-DSS-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + + /* TLS 1.2 addenda, RFC 5246 */ + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, /* 0x0067 */ + "DHE-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_CBC_SHA256, /* 0x0068 */ + "DH-DSS-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_CBC_SHA256, /* 0x0069 */ + "DH-RSA-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256, /* 0x006A */ + "DHE-DSS-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, /* 0x006B */ + "DHE-RSA-AES256-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_CBC_SHA256, /* 0x006C */ + "ADH-AES128-SHA256", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_CBC_SHA256, /* 0x006D */ + "ADH-AES256-SHA256", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* Addendum from RFC 4279, TLS PSK */ + CIPHER_DEF(TLS_PSK_WITH_RC4_128_SHA, /* 0x008A */ + "PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008B */ + "PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA, /* 0x008C */ + "PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA, /* 0x008D */ + "PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_RC4_128_SHA, /* 0x008E */ + "DHE-PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x008F */ + "DHE-PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA, /* 0x0090 */ + "DHE-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA, /* 0x0091 */ + "DHE-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_RC4_128_SHA, /* 0x0092 */ + "RSA-PSK-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA, /* 0x0093 */ + "RSA-PSK-3DES-EDE-CBC-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA, /* 0x0094 */ + "RSA-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA, /* 0x0095 */ + "RSA-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* Addenda from rfc 5288 AES Galois Counter Mode (GCM) Cipher Suites + for TLS. */ + CIPHER_DEF(TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */ + "AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */ + "AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* 0x009E */ + "DHE-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, /* 0x009F */ + "DHE-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_128_GCM_SHA256, /* 0x00A0 */ + "DH-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_RSA_WITH_AES_256_GCM_SHA384, /* 0x00A1 */ + "DH-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A2 */ + "DHE-DSS-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A3 */ + "DHE-DSS-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_128_GCM_SHA256, /* 0x00A4 */ + "DH-DSS-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_DSS_WITH_AES_256_GCM_SHA384, /* 0x00A5 */ + "DH-DSS-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_128_GCM_SHA256, /* 0x00A6 */ + "ADH-AES128-GCM-SHA256", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_DH_anon_WITH_AES_256_GCM_SHA384, /* 0x00A7 */ + "ADH-AES256-GCM-SHA384", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 + /* RFC 5487 - PSK with SHA-256/384 and AES GCM */ + CIPHER_DEF(TLS_PSK_WITH_AES_128_GCM_SHA256, /* 0x00A8 */ + "PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_GCM_SHA384, /* 0x00A9 */ + "PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AA */ + "DHE-PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AB */ + "DHE-PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_GCM_SHA256, /* 0x00AC */ + "RSA-PSK-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_GCM_SHA384, /* 0x00AD */ + "RSA-PSK-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_128_CBC_SHA256, /* 0x00AE */ + "PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_AES_256_CBC_SHA384, /* 0x00AF */ + "PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA256, /* 0x00B0 */ + "PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_PSK_WITH_NULL_SHA384, /* 0x00B1 */ + "PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B2 */ + "DHE-PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B3 */ + "DHE-PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA256, /* 0x00B4 */ + "DHE-PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_DHE_PSK_WITH_NULL_SHA384, /* 0x00B5 */ + "DHE-PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_128_CBC_SHA256, /* 0x00B6 */ + "RSA-PSK-AES128-CBC-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_AES_256_CBC_SHA384, /* 0x00B7 */ + "RSA-PSK-AES256-CBC-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA256, /* 0x00B8 */ + "RSA-PSK-NULL-SHA256", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_RSA_PSK_WITH_NULL_SHA384, /* 0x00B9 */ + "RSA-PSK-NULL-SHA384", + CIPHER_WEAK_NOT_ENCRYPTED), +#endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */ + + /* RFC 5746 - Secure Renegotiation. This is not a real suite, + it is a response to initiate negotiation again */ + CIPHER_DEF(TLS_EMPTY_RENEGOTIATION_INFO_SCSV, /* 0x00FF */ + NULL, + CIPHER_STRONG_ENOUGH), + +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + /* TLS 1.3 standard cipher suites for ChaCha20+Poly1305. + Note: TLS 1.3 ciphersuites do not specify the key exchange + algorithm -- they only specify the symmetric ciphers. + Cipher alias name matches to OpenSSL cipher name, and for + TLS 1.3 ciphers */ + CIPHER_DEF(TLS_AES_128_GCM_SHA256, /* 0x1301 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_256_GCM_SHA384, /* 0x1302 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_CHACHA20_POLY1305_SHA256, /* 0x1303 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_128_CCM_SHA256, /* 0x1304 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_AES_128_CCM_8_SHA256, /* 0x1305 */ + NULL, /* The OpenSSL cipher name matches to the IANA name */ + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ + +#if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS + /* ECDSA addenda, RFC 4492 */ + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_NULL_SHA, /* 0xC001 */ + "ECDH-ECDSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_RC4_128_SHA, /* 0xC002 */ + "ECDH-ECDSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC003 */ + "ECDH-ECDSA-DES-CBC3-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC004 */ + "ECDH-ECDSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC005 */ + "ECDH-ECDSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_NULL_SHA, /* 0xC006 */ + "ECDHE-ECDSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, /* 0xC007 */ + "ECDHE-ECDSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, /* 0xC008 */ + "ECDHE-ECDSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */ + "ECDHE-ECDSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */ + "ECDHE-ECDSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_NULL_SHA, /* 0xC00B */ + "ECDH-RSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDH_RSA_WITH_RC4_128_SHA, /* 0xC00C */ + "ECDH-RSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC00D */ + "ECDH-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, /* 0xC00E */ + "ECDH-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, /* 0xC00F */ + "ECDH-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_NULL_SHA, /* 0xC010 */ + "ECDHE-RSA-NULL-SHA", + CIPHER_WEAK_NOT_ENCRYPTED), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_RC4_128_SHA, /* 0xC011 */ + "ECDHE-RSA-RC4-SHA", + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, /* 0xC012 */ + "ECDHE-RSA-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */ + "ECDHE-RSA-AES128-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */ + "ECDHE-RSA-AES256-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_anon_WITH_NULL_SHA, /* 0xC015 */ + "AECDH-NULL-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_RC4_128_SHA, /* 0xC016 */ + "AECDH-RC4-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, /* 0xC017 */ + "AECDH-DES-CBC3-SHA", + CIPHER_WEAK_3DES_ENCRYPTION), + CIPHER_DEF(TLS_ECDH_anon_WITH_AES_128_CBC_SHA, /* 0xC018 */ + "AECDH-AES128-SHA", + CIPHER_WEAK_ANON_AUTH), + CIPHER_DEF(TLS_ECDH_anon_WITH_AES_256_CBC_SHA, /* 0xC019 */ + "AECDH-AES256-SHA", + CIPHER_WEAK_ANON_AUTH), +#endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS + /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with + HMAC SHA-256/384. */ + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */ + "ECDHE-ECDSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */ + "ECDHE-ECDSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC025 */ + "ECDH-ECDSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC026 */ + "ECDH-ECDSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */ + "ECDHE-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */ + "ECDHE-RSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256, /* 0xC029 */ + "ECDH-RSA-AES128-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384, /* 0xC02A */ + "ECDH-RSA-AES256-SHA384", + CIPHER_STRONG_ENOUGH), + /* Addenda from rfc 5289 Elliptic Curve Cipher Suites with + SHA-256/384 and AES Galois Counter Mode (GCM) */ + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */ + "ECDHE-ECDSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */ + "ECDHE-ECDSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02D */ + "ECDH-ECDSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02E */ + "ECDH-ECDSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */ + "ECDHE-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */ + "ECDHE-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256, /* 0xC031 */ + "ECDH-RSA-AES128-GCM-SHA256", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384, /* 0xC032 */ + "ECDH-RSA-AES256-GCM-SHA384", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */ + +#if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 + /* ECDHE_PSK Cipher Suites for Transport Layer Security (TLS), RFC 5489 */ + CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA, /* 0xC035 */ + "ECDHE-PSK-AES128-CBC-SHA", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA, /* 0xC036 */ + "ECDHE-PSK-AES256-CBC-SHA", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ + +#if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 + /* Addenda from rfc 7905 ChaCha20-Poly1305 Cipher Suites for + Transport Layer Security (TLS). */ + CIPHER_DEF(TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */ + "ECDHE-RSA-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), + CIPHER_DEF(TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */ + "ECDHE-ECDSA-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */ + +#if CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 + /* ChaCha20-Poly1305 Cipher Suites for Transport Layer Security (TLS), + RFC 7905 */ + CIPHER_DEF(TLS_PSK_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCAB */ + "PSK-CHACHA20-POLY1305", + CIPHER_STRONG_ENOUGH), +#endif /* CURL_BUILD_MAC_10_15 || CURL_BUILD_IOS_13 */ + + /* Tags for SSL 2 cipher kinds which are not specified for SSL 3. + Defined since SDK 10.2.8 */ + CIPHER_DEF(SSL_RSA_WITH_RC2_CBC_MD5, /* 0xFF80 */ + NULL, + CIPHER_WEAK_RC_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_IDEA_CBC_MD5, /* 0xFF81 */ + NULL, + CIPHER_WEAK_IDEA_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_DES_CBC_MD5, /* 0xFF82 */ + NULL, + CIPHER_WEAK_DES_ENCRYPTION), + CIPHER_DEF(SSL_RSA_WITH_3DES_EDE_CBC_MD5, /* 0xFF83 */ + NULL, + CIPHER_WEAK_3DES_ENCRYPTION), +}; + +#define NUM_OF_CIPHERS sizeof(ciphertable)/sizeof(ciphertable[0]) + +static const char* SSLCipherSuiteToString(SSLCipherSuite cipher) +{ + /* The first ciphers in the ciphertable are continuos. Here we do small + optimization and instead of loop directly get SSL name by cipher number. + */ + if(cipher <= SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA) { + return ciphertable[cipher].name; + } + /* Iterate through the rest of the ciphers */ + for(size_t i = SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA + 1; + i < NUM_OF_CIPHERS; + ++i) { + if(ciphertable[i].num == cipher) { + return ciphertable[i].name; + } + } + return ciphertable[SSL_NULL_WITH_NULL_NULL].name; +} + +static bool is_cipher_suite_strong(SSLCipherSuite suite_num) +{ + for(size_t i = 0; i < NUM_OF_CIPHERS; ++i) { + if(ciphertable[i].num == suite_num) { + return !ciphertable[i].weak; + } + } + /* If the cipher is not in our list, assume it is a new one + and therefore strong. Previous implementation was the same, + if cipher suite is not in the list, it was considered strong enough */ + return true; +} + +const char* hssl_backend() { + return "appletls"; +} + +typedef struct appletls_ctx { + SecIdentityRef cert; + hssl_ctx_opt_t* param; +} appletls_ctx_t; + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { + appletls_ctx_t* ctx = (appletls_ctx_t*)malloc(sizeof(appletls_ctx_t)); + if (ctx == NULL) return NULL; + ctx->cert = NULL; + ctx->param = param; + return ctx; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) { + if (ssl_ctx == NULL) return; + appletls_ctx_t* ctx = (appletls_ctx_t*)ssl_ctx; + if (ctx->cert) { + CFRelease(ctx->cert); + ctx->cert = NULL; + } + free(ctx); +} + +typedef struct appletls_s { + SSLContextRef session; + appletls_ctx_t* ctx; + int fd; +} appletls_t; + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { + if (ssl_ctx == NULL) return NULL; + appletls_t* appletls = (appletls_t*)malloc(sizeof(appletls_t)); + if (appletls == NULL) return NULL; + appletls->session = NULL; + appletls->ctx = (appletls_ctx_t*)ssl_ctx; + appletls->fd = fd; + return (hssl_t)appletls; +} + +static OSStatus SocketRead(SSLConnectionRef conn, void* data, size_t* len) { + // printf("SocketRead(%d)\n", (int)*len); + appletls_t* appletls = (appletls_t*)conn; + uint8_t* buffer = (uint8_t*)data; + size_t remain = *len; + *len = 0; + int fd = appletls->fd; + // int timeout = 1000; + // struct timeval tv = { timeout / 1000, (timeout % 1000) * 1000 }; + // fd_set readfds; + while (remain) { + /* + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + int nselect = select(fd + 1, &readfds, 0, 0, &tv); + printf("nselect=%d\n", nselect); + if (nselect < 0) { + return errSSLClosedAbort; + } + if (nselect == 0) { + return errSSLWouldBlock; + } + */ + // printf("read(%d)\n", (int)remain); + // NOTE: avoid blocking + if (remain < 16) { + so_rcvtimeo(fd, 1000); + } + ssize_t nread = read(fd, buffer, remain); + // printf("nread=%d errno=%d\n", (int)nread, (int)errno); + if (nread == 0) return errSSLClosedGraceful; + if (nread < 0) { + switch (errno) { + case ENOENT: return errSSLClosedGraceful; + case ECONNRESET:return errSSLClosedAbort; + case EAGAIN: return errSSLWouldBlock; + default: return errSSLClosedAbort; + } + } + *len += nread; + remain -= nread; + buffer += nread; + } + return noErr; +} + +static OSStatus SocketWrite(SSLConnectionRef conn, const void* data, size_t* len) { + // printf("SocketWrite(%d)\n", (int)*len); + appletls_t* appletls = (appletls_t*)conn; + uint8_t* buffer = (uint8_t*)data; + size_t remain = *len; + *len = 0; + int fd = appletls->fd; + while (remain) { + if (remain < 16) { + so_sndtimeo(fd, 1000); + } + // printf("write(%d)\n", (int)remain); + ssize_t nwrite = write(fd, buffer, remain); + // printf("nwrite=%d errno=%d\n", (int)nwrite, (int)errno); + if (nwrite <= 0) { + switch (errno) { + case EAGAIN: return errSSLWouldBlock; + default: return errSSLClosedAbort; + } + } + remain -= nwrite; + buffer += nwrite; + *len += nwrite; + } + return noErr; +} + +static int hssl_init(hssl_t ssl, int endpoint) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + OSStatus ret = noErr; + if (appletls->session == NULL) { +#if defined(__MAC_10_8) + appletls->session = SSLCreateContext(NULL, endpoint == HSSL_SERVER ? kSSLServerSide : kSSLClientSide, kSSLStreamType); +#else + SSLNewContext(endpoint == HSSL_SERVER, &(appletls->session)); +#endif + } + if (appletls->session == NULL) { + fprintf(stderr, "SSLCreateContext failed!\n"); + return HSSL_ERROR; + } + + // ret = SSLSetProtocolVersionEnabled(appletls->session, kSSLProtocolAll, true); + ret = SSLSetProtocolVersionMin(appletls->session, kTLSProtocol12); + if (ret != noErr) { + fprintf(stderr, "SSLSetProtocolVersionMin failed!\n"); + return HSSL_ERROR; + } + + bool verify_peer = false; + if (appletls->ctx->param && appletls->ctx->param->verify_peer) { + verify_peer = true; + } +#if defined(__MAC_10_8) + ret = SSLSetSessionOption(appletls->session, kSSLSessionOptionBreakOnServerAuth, !verify_peer); +#else + ret = SSLSetEnableCertVerify(appletls->session, verify_peer); +#endif + if (ret != noErr) { + fprintf(stderr, "SSLSetEnableCertVerify failed!\n"); + return HSSL_ERROR; + } + + if (appletls->ctx->cert) { + CFArrayRef certs = CFArrayCreate(NULL, (const void**)&appletls->ctx->cert, 1, NULL); + if (!certs) { + fprintf(stderr, "CFArrayCreate failed!\n"); + return HSSL_ERROR; + } + ret = SSLSetCertificate(appletls->session, certs); + CFRelease(certs); + if (ret != noErr) { + fprintf(stderr, "SSLSetCertificate failed!\n"); + return HSSL_ERROR; + } + } + + size_t all_ciphers_count = 0, allowed_ciphers_count = 0; + SSLCipherSuite *all_ciphers = NULL, *allowed_ciphers = NULL; + ret = SSLGetNumberSupportedCiphers(appletls->session, &all_ciphers_count); + if (ret != noErr) { + fprintf(stderr, "SSLGetNumberSupportedCiphers failed!\n"); + goto error; + } + all_ciphers = (SSLCipherSuite*)malloc(all_ciphers_count * sizeof(SSLCipherSuite)); + allowed_ciphers = (SSLCipherSuite*)malloc(all_ciphers_count * sizeof(SSLCipherSuite)); + if (all_ciphers == NULL || allowed_ciphers == NULL) { + fprintf(stderr, "malloc failed!\n"); + goto error; + } + ret = SSLGetSupportedCiphers(appletls->session, all_ciphers, &all_ciphers_count); + if (ret != noErr) { + fprintf(stderr, "SSLGetSupportedCiphers failed!\n"); + goto error; + } + for (size_t i = 0; i < all_ciphers_count; ++i) { + if (is_cipher_suite_strong(all_ciphers[i])) { + allowed_ciphers[allowed_ciphers_count++] = all_ciphers[i]; + } + } + ret = SSLSetEnabledCiphers(appletls->session, allowed_ciphers, allowed_ciphers_count); + if (ret != noErr) { + fprintf(stderr, "SSLSetEnabledCiphers failed!\n"); + goto error; + } + if (all_ciphers) { + free(all_ciphers); + all_ciphers = NULL; + } + if (allowed_ciphers) { + free(allowed_ciphers); + allowed_ciphers = NULL; + } + + ret = SSLSetIOFuncs(appletls->session, SocketRead, SocketWrite); + if (ret != noErr) { + fprintf(stderr, "SSLSetIOFuncs failed!\n"); + return HSSL_ERROR; + } + ret = SSLSetConnection(appletls->session, appletls); + if (ret != noErr) { + fprintf(stderr, "SSLSetConnection failed!\n"); + return HSSL_ERROR; + } + + /* + char session_id[64] = {0}; + int session_id_len = snprintf(session_id, sizeof(session_id), "libhv:appletls:%p", appletls->session); + ret = SSLSetPeerID(appletls->session, session_id, session_id_len); + if (ret != noErr) { + fprintf(stderr, "SSLSetPeerID failed!\n"); + return HSSL_ERROR; + } + */ + + return HSSL_OK; +error: + if (all_ciphers) { + free(all_ciphers); + } + if (allowed_ciphers) { + free(allowed_ciphers); + } + return HSSL_ERROR; +} + +void hssl_free(hssl_t ssl) { + if (ssl == NULL) return; + appletls_t* appletls = (appletls_t*)ssl; + if (appletls->session) { +#if defined(__MAC_10_8) + CFRelease(appletls->session); +#else + SSLDisposeContext(appletls->session); +#endif + appletls->session = NULL; + } + free(appletls); +} + +static int hssl_handshake(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + OSStatus ret = SSLHandshake(appletls->session); + // printf("SSLHandshake retval=%d\n", (int)ret); + switch(ret) { + case noErr: + break; + case errSSLWouldBlock: + return HSSL_WANT_READ; + case errSSLPeerAuthCompleted: /* peer cert is valid, or was ignored if verification disabled */ + return hssl_handshake(ssl); + case errSSLBadConfiguration: + return HSSL_WANT_READ; + default: + return HSSL_ERROR; + } + + /* + SSLProtocol protocol = kSSLProtocolUnknown; + SSLGetNegotiatedProtocolVersion(appletls->session, &protocol); + SSLCipherSuite cipher = SSL_NO_SUCH_CIPHERSUITE; + SSLGetNegotiatedCipher(appletls->session, &cipher); + printf("* %s connection using %s\n", SSLProtocolToString(protocol), SSLCipherSuiteToString(cipher)); + */ + + return HSSL_OK; +} + +int hssl_accept(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + if (appletls->session == NULL) { + hssl_init(ssl, HSSL_SERVER); + } + return hssl_handshake(ssl); +} + +int hssl_connect(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + if (appletls->session == NULL) { + hssl_init(ssl, HSSL_CLIENT); + } + return hssl_handshake(ssl); +} + +int hssl_read(hssl_t ssl, void* buf, int len) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + size_t processed = 0; + // printf("SSLRead(%d)\n", len); + OSStatus ret = SSLRead(appletls->session, buf, len, &processed); + // printf("SSLRead retval=%d processed=%d\n", (int)ret, (int)processed); + switch (ret) { + case noErr: + return processed; + case errSSLWouldBlock: + return processed ? processed : HSSL_WOULD_BLOCK; + case errSSLClosedGraceful: + case errSSLClosedNoNotify: + return 0; + default: + return HSSL_ERROR; + } +} + +int hssl_write(hssl_t ssl, const void* buf, int len) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + size_t processed = 0; + // printf("SSLWrite(%d)\n", len); + OSStatus ret = SSLWrite(appletls->session, buf, len, &processed); + // printf("SSLWrite retval=%d processed=%d\n", (int)ret, (int)processed); + switch (ret) { + case noErr: + return processed; + case errSSLWouldBlock: + return processed ? processed : HSSL_WOULD_BLOCK; + case errSSLClosedGraceful: + case errSSLClosedNoNotify: + return 0; + default: + return HSSL_ERROR; + } +} + +int hssl_close(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + SSLClose(appletls->session); + return 0; +} + +int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { + if (ssl == NULL) return HSSL_ERROR; + appletls_t* appletls = (appletls_t*)ssl; + if (appletls->session == NULL) { + hssl_init(ssl, HSSL_CLIENT); + } + SSLSetPeerDomainName(appletls->session, hostname, strlen(hostname)); + return 0; +} + +#endif // WITH_APPLETLS diff --git a/external/libhv/libhv-1.3.2/ssl/gnutls.c b/external/libhv/libhv-1.3.2/ssl/gnutls.c new file mode 100644 index 0000000..465c89a --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/gnutls.c @@ -0,0 +1,197 @@ +#include "hssl.h" + +#ifdef WITH_GNUTLS + +#include "gnutls/gnutls.h" + +const char* hssl_backend() { + return "gnutls"; +} + +typedef gnutls_certificate_credentials_t gnutls_ctx_t; + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { + static int s_initialized = 0; + if (s_initialized == 0) { + gnutls_global_init(); + s_initialized = 1; + } + + gnutls_ctx_t ctx; + const char* crt_file = NULL; + const char* key_file = NULL; + const char* ca_file = NULL; + const char* ca_path = NULL; + + int ret = gnutls_certificate_allocate_credentials(&ctx); + if (ret != GNUTLS_E_SUCCESS) { + return NULL; + } + + if (param) { + if (param->crt_file && *param->crt_file) { + crt_file = param->crt_file; + } + if (param->key_file && *param->key_file) { + key_file = param->key_file; + } + if (param->ca_file && *param->ca_file) { + ca_file = param->ca_file; + } + if (param->ca_path && *param->ca_path) { + ca_path = param->ca_path; + } + + if (ca_file) { + ret = gnutls_certificate_set_x509_trust_file(ctx, ca_file, GNUTLS_X509_FMT_PEM); + if (ret < 0) { + fprintf(stderr, "ssl ca_file failed!\n"); + goto error; + } + } + + if (ca_path) { + ret = gnutls_certificate_set_x509_trust_dir(ctx, ca_path, GNUTLS_X509_FMT_PEM); + if (ret < 0) { + fprintf(stderr, "ssl ca_path failed!\n"); + goto error; + } + } + + if (crt_file && key_file) { + ret = gnutls_certificate_set_x509_key_file(ctx, crt_file, key_file, GNUTLS_X509_FMT_PEM); + if (ret != GNUTLS_E_SUCCESS) { + fprintf(stderr, "ssl crt_file/key_file error!\n"); + goto error; + } + } + + if (param->verify_peer && !ca_file && !ca_path) { + gnutls_certificate_set_x509_system_trust(ctx); + } + } + return ctx; +error: + gnutls_certificate_free_credentials(ctx); + return NULL; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) { + if (!ssl_ctx) return; + gnutls_ctx_t ctx = (gnutls_ctx_t)ssl_ctx; + gnutls_certificate_free_credentials(ctx); +} + +typedef struct gnutls_s { + gnutls_session_t session; + gnutls_ctx_t ctx; + int fd; +} gnutls_t; + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { + gnutls_t* gnutls = (gnutls_t*)malloc(sizeof(gnutls_t)); + if (gnutls == NULL) return NULL; + gnutls->session = NULL; + gnutls->ctx = (gnutls_ctx_t)ssl_ctx; + gnutls->fd = fd; + return (hssl_t)gnutls; +} + +static int hssl_init(hssl_t ssl, int endpoint) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) { + gnutls_init(&gnutls->session, endpoint); + gnutls_priority_set_direct(gnutls->session, "NORMAL", NULL); + gnutls_credentials_set(gnutls->session, GNUTLS_CRD_CERTIFICATE, gnutls->ctx); + gnutls_transport_set_ptr(gnutls->session, (gnutls_transport_ptr_t)(ptrdiff_t)gnutls->fd); + } + return HSSL_OK; +} + +void hssl_free(hssl_t ssl) { + if (ssl == NULL) return; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session) { + gnutls_deinit(gnutls->session); + gnutls->session = NULL; + } + free(gnutls); +} + +static int hssl_handshake(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) return HSSL_ERROR; + int ret = 0; + while (1) { + ret = gnutls_handshake(gnutls->session); + if (ret == GNUTLS_E_SUCCESS) { + return HSSL_OK; + } + else if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) { + return gnutls_record_get_direction(gnutls->session) == 0 ? HSSL_WANT_READ : HSSL_WANT_WRITE; + } + else if (gnutls_error_is_fatal(ret)) { + // fprintf(stderr, "gnutls_handshake failed: %s\n", gnutls_strerror(ret)); + return HSSL_ERROR; + } + } + return HSSL_OK; +} + +int hssl_accept(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) { + hssl_init(ssl, GNUTLS_SERVER); + } + return hssl_handshake(ssl); +} + +int hssl_connect(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) { + hssl_init(ssl, GNUTLS_CLIENT); + } + return hssl_handshake(ssl); +} + +int hssl_read(hssl_t ssl, void* buf, int len) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) return HSSL_ERROR; + int ret = 0; + while ((ret = gnutls_record_recv(gnutls->session, buf, len)) == GNUTLS_E_INTERRUPTED); + return ret; +} + +int hssl_write(hssl_t ssl, const void* buf, int len) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) return HSSL_ERROR; + int ret = 0; + while ((ret = gnutls_record_send(gnutls->session, buf, len)) == GNUTLS_E_INTERRUPTED); + return ret; +} + +int hssl_close(hssl_t ssl) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) return HSSL_ERROR; + gnutls_bye(gnutls->session, GNUTLS_SHUT_RDWR); + return HSSL_OK; +} + +int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { + if (ssl == NULL) return HSSL_ERROR; + gnutls_t* gnutls = (gnutls_t*)ssl; + if (gnutls->session == NULL) { + hssl_init(ssl, GNUTLS_CLIENT); + } + gnutls_server_name_set(gnutls->session, GNUTLS_NAME_DNS, hostname, strlen(hostname)); + return 0; +} + +#endif // WITH_GNUTLS diff --git a/external/libhv/libhv-1.3.2/ssl/hssl.c b/external/libhv/libhv-1.3.2/ssl/hssl.c new file mode 100644 index 0000000..ad95b24 --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/hssl.c @@ -0,0 +1,24 @@ +#include "hssl.h" + +hssl_ctx_t g_ssl_ctx = NULL; + +hssl_ctx_t hssl_ctx_init(hssl_ctx_init_param_t* param) { + if (g_ssl_ctx == NULL) { + g_ssl_ctx = hssl_ctx_new(param); + } + return g_ssl_ctx; +} + +void hssl_ctx_cleanup(hssl_ctx_t ssl_ctx) { + hssl_ctx_free(ssl_ctx); + if (g_ssl_ctx == ssl_ctx) { + g_ssl_ctx = NULL; + } +} + +hssl_ctx_t hssl_ctx_instance() { + if (g_ssl_ctx == NULL) { + g_ssl_ctx = hssl_ctx_new(NULL); + } + return g_ssl_ctx; +} diff --git a/external/libhv/libhv-1.3.2/ssl/hssl.h b/external/libhv/libhv-1.3.2/ssl/hssl.h new file mode 100644 index 0000000..0a6cf09 --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/hssl.h @@ -0,0 +1,91 @@ +#ifndef HV_SSL_H_ +#define HV_SSL_H_ + +#include "hexport.h" + +#include "hplatform.h" +#if !defined(WITH_OPENSSL) && \ + !defined(WITH_GNUTLS) && \ + !defined(WITH_MBEDTLS) +#ifdef OS_WIN + #define WITH_WINTLS + #ifdef _MSC_VER + #pragma comment(lib, "secur32.lib") + #pragma comment(lib, "crypt32.lib") + #endif +#elif defined(OS_DARWIN) + #define WITH_APPLETLS +#else + #define HV_WITHOUT_SSL +#endif +#endif + +typedef void* hssl_ctx_t; ///> SSL_CTX +typedef void* hssl_t; ///> SSL + +enum { + HSSL_SERVER = 0, + HSSL_CLIENT = 1, +}; + +enum { + HSSL_OK = 0, + HSSL_ERROR = -1, + HSSL_WANT_READ = -2, + HSSL_WANT_WRITE = -3, + HSSL_WOULD_BLOCK = -4, +}; + +typedef struct { + const char* crt_file; + const char* key_file; + const char* ca_file; + const char* ca_path; + short verify_peer; + short endpoint; // HSSL_SERVER / HSSL_CLIENT +} hssl_ctx_opt_t, hssl_ctx_init_param_t; + +BEGIN_EXTERN_C + +/* +const char* hssl_backend() { +#ifdef WITH_OPENSSL + return "openssl"; +#elif defined(WITH_GNUTLS) + return "gnutls"; +#elif defined(WITH_MBEDTLS) + return "mbedtls"; +#else + return "nossl"; +#endif +} +*/ +HV_EXPORT const char* hssl_backend(); +#define HV_WITH_SSL (strcmp(hssl_backend(), "nossl") != 0) + +HV_EXPORT extern hssl_ctx_t g_ssl_ctx; +HV_EXPORT hssl_ctx_t hssl_ctx_init(hssl_ctx_init_param_t* param); +HV_EXPORT void hssl_ctx_cleanup(hssl_ctx_t ssl_ctx); +HV_EXPORT hssl_ctx_t hssl_ctx_instance(); + +HV_EXPORT hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt); +HV_EXPORT void hssl_ctx_free(hssl_ctx_t ssl_ctx); + +HV_EXPORT hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd); +HV_EXPORT void hssl_free(hssl_t ssl); + +HV_EXPORT int hssl_accept(hssl_t ssl); +HV_EXPORT int hssl_connect(hssl_t ssl); +HV_EXPORT int hssl_read(hssl_t ssl, void* buf, int len); +HV_EXPORT int hssl_write(hssl_t ssl, const void* buf, int len); +HV_EXPORT int hssl_close(hssl_t ssl); + +HV_EXPORT int hssl_set_sni_hostname(hssl_t ssl, const char* hostname); + +#ifdef WITH_OPENSSL +HV_EXPORT int hssl_ctx_set_alpn_protos(hssl_ctx_t ssl_ctx, const unsigned char* protos, unsigned int protos_len); +#endif + +END_EXTERN_C + +#endif // HV_SSL_H_ diff --git a/external/libhv/libhv-1.3.2/ssl/mbedtls.c b/external/libhv/libhv-1.3.2/ssl/mbedtls.c new file mode 100644 index 0000000..4a14ead --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/mbedtls.c @@ -0,0 +1,194 @@ +#include "hssl.h" +#include "hsocket.h" + +#ifdef WITH_MBEDTLS + +#include "mbedtls/version.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/x509.h" +#include "mbedtls/ssl.h" +#include "mbedtls/net_sockets.h" +#include "mbedtls/error.h" +#include "mbedtls/debug.h" + +#if defined(MBEDTLS_SSL_CACHE_C) +#include "mbedtls/ssl_cache.h" +#endif + +#ifdef _MSC_VER +//#pragma comment(lib, "libmbedtls.a") +//#pragma comment(lib, "libmbedx509.a") +//#pragma comment(lib, "libmbedcrypto.a") +#endif + +const char* hssl_backend() { + return "mbedtls"; +} + +struct mbedtls_ctx { + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_config conf; + mbedtls_x509_crt cert; + mbedtls_pk_context pkey; +#if defined(MBEDTLS_SSL_CACHE_C) + mbedtls_ssl_cache_context cache; +#endif +}; + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { + struct mbedtls_ctx* ctx = (struct mbedtls_ctx*)malloc(sizeof(struct mbedtls_ctx)); + if (ctx == NULL) return NULL; + + mbedtls_ssl_config_init(&ctx->conf); +#if defined(MBEDTLS_SSL_CACHE_C) + mbedtls_ssl_cache_init(&ctx->cache); +#endif + mbedtls_x509_crt_init(&ctx->cert); + mbedtls_pk_init(&ctx->pkey); + mbedtls_entropy_init(&ctx->entropy); + mbedtls_ctr_drbg_init(&ctx->ctr_drbg); + + int mode = MBEDTLS_SSL_VERIFY_NONE; + int endpoint = MBEDTLS_SSL_IS_CLIENT; + bool check = false; + if (param) { + if (param->crt_file && *param->crt_file) { + if (mbedtls_x509_crt_parse_file(&ctx->cert, param->crt_file) != 0) { + fprintf(stderr, "ssl crt_file error!\n"); + goto error; + } + } + if (param->key_file && *param->key_file) { +#if MBEDTLS_VERSION_MAJOR >= 3 + if (mbedtls_pk_parse_keyfile(&ctx->pkey, param->key_file, NULL, NULL, NULL) != 0) { +#else + if (mbedtls_pk_parse_keyfile(&ctx->pkey, param->key_file, NULL) != 0) { +#endif + fprintf(stderr, "ssl key_file error!\n"); + goto error; + } + check = true; + } + if (param->verify_peer) { + mode = MBEDTLS_SSL_VERIFY_REQUIRED; + } + if (param->endpoint == HSSL_SERVER) { + endpoint = MBEDTLS_SSL_IS_SERVER; + } + } + mbedtls_ctr_drbg_seed(&ctx->ctr_drbg, mbedtls_entropy_func, &ctx->entropy, NULL, 0); + if (mbedtls_ssl_config_defaults(&ctx->conf, endpoint, + MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) { + fprintf(stderr, "ssl config error!\n"); + goto error; + } + mbedtls_ssl_conf_authmode(&ctx->conf, mode); + mbedtls_ssl_conf_rng(&ctx->conf, mbedtls_ctr_drbg_random, &ctx->ctr_drbg); + +#if defined(MBEDTLS_SSL_CACHE_C) + mbedtls_ssl_conf_session_cache(&ctx->conf, &ctx->cache, mbedtls_ssl_cache_get, mbedtls_ssl_cache_set); +#endif + + if (check) { + mbedtls_ssl_conf_ca_chain(&ctx->conf, ctx->cert.next, NULL); + if (mbedtls_ssl_conf_own_cert(&ctx->conf, &ctx->cert, &ctx->pkey) != 0) { + fprintf(stderr, "ssl key_file check failed!\n"); + goto error; + } + } + return ctx; +error: + free(ctx); + return NULL; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) { + if (!ssl_ctx) return; + struct mbedtls_ctx *mctx = (struct mbedtls_ctx *)ssl_ctx; + mbedtls_x509_crt_free(&mctx->cert); + mbedtls_pk_free(&mctx->pkey); + mbedtls_ssl_config_free(&mctx->conf); +#if defined(MBEDTLS_SSL_CACHE_C) + mbedtls_ssl_cache_free(&mctx->cache); +#endif + mbedtls_ctr_drbg_free(&mctx->ctr_drbg); + mbedtls_entropy_free(&mctx->entropy); + free(mctx); +} + +static int __mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len) { + int fd = (intptr_t)ctx; + // int n = write(fd, buf, len); + int n = send(fd, (char*)(buf), (int)(len), 0); + if (n >= 0) return n; + return ((socket_errno() == EAGAIN || socket_errno() == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1); +} + +static int __mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len) { + int fd = (intptr_t)ctx; + // int n = read(fd, buf, len); + int n = recv(fd, (char*)(buf), (int)(len), 0); + if (n >= 0) return n; + return ((socket_errno() == EAGAIN || socket_errno() == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1); +} + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { + struct mbedtls_ctx* mctx = (struct mbedtls_ctx*)ssl_ctx; + mbedtls_ssl_context* ssl = (mbedtls_ssl_context*)malloc(sizeof(mbedtls_ssl_context)); + if (ssl == NULL) return NULL; + mbedtls_ssl_init(ssl); + mbedtls_ssl_setup(ssl, &mctx->conf); + mbedtls_ssl_set_bio(ssl, (void*)(intptr_t)fd, __mbedtls_net_send, __mbedtls_net_recv, NULL); + return ssl; +} + +void hssl_free(hssl_t ssl) { + if (ssl) { + mbedtls_ssl_free(ssl); + ssl = NULL; + } +} + +static int hssl_handshake(hssl_t ssl) { + int ret = mbedtls_ssl_handshake(ssl); + if (ret != 0) { + if (ret == MBEDTLS_ERR_SSL_WANT_READ) { + return HSSL_WANT_READ; + } + else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { + return HSSL_WANT_WRITE; + } + } + return ret; +} + +int hssl_accept(hssl_t ssl) { + return hssl_handshake(ssl); +} + +int hssl_connect(hssl_t ssl) { + return hssl_handshake(ssl); +} + +int hssl_read(hssl_t ssl, void* buf, int len) { + return mbedtls_ssl_read(ssl, buf, len); +} + +int hssl_write(hssl_t ssl, const void* buf, int len) { + return mbedtls_ssl_write(ssl, buf, len); +} + +int hssl_close(hssl_t ssl) { + return 0; +} + +int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { +#ifdef MBEDTLS_X509_CRT_PARSE_C + mbedtls_ssl_set_hostname(ssl, hostname); +#endif + return 0; +} + +#endif // WITH_MBEDTLS diff --git a/external/libhv/libhv-1.3.2/ssl/nossl.c b/external/libhv/libhv-1.3.2/ssl/nossl.c new file mode 100644 index 0000000..03a873d --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/nossl.c @@ -0,0 +1,50 @@ +#include "hssl.h" + +#ifdef HV_WITHOUT_SSL + +const char* hssl_backend() { + return "nossl"; +} + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt) { + fprintf(stderr, "Please recompile WITH_SSL.\n"); + return NULL; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) { +} + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { + return (void*)(intptr_t)fd; +} + +void hssl_free(hssl_t ssl) { +} + +int hssl_accept(hssl_t ssl) { + return 0; +} + +int hssl_connect(hssl_t ssl) { + return 0; +} + +int hssl_read(hssl_t ssl, void* buf, int len) { + int fd = (intptr_t)ssl; + return read(fd, buf, len); +} + +int hssl_write(hssl_t ssl, const void* buf, int len) { + int fd = (intptr_t)ssl; + return write(fd, buf, len); +} + +int hssl_close(hssl_t ssl) { + return 0; +} + +int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { + return 0; +} + +#endif // HV_WITHOUT_SSL diff --git a/external/libhv/libhv-1.3.2/ssl/openssl.c b/external/libhv/libhv-1.3.2/ssl/openssl.c new file mode 100644 index 0000000..8758794 --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/openssl.c @@ -0,0 +1,188 @@ +#include "hssl.h" + +#ifdef WITH_OPENSSL + +#include "openssl/ssl.h" +#include "openssl/err.h" +#ifdef _MSC_VER +//#pragma comment(lib, "libssl.a") +//#pragma comment(lib, "libcrypto.a") +#endif + +const char* hssl_backend() { + return "openssl"; +} + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* param) { + static int s_initialized = 0; + if (s_initialized == 0) { +#if OPENSSL_VERSION_NUMBER < 0x10100000L + SSL_library_init(); + SSL_load_error_strings(); +#else + OPENSSL_init_ssl(OPENSSL_INIT_SSL_DEFAULT, NULL); +#endif + s_initialized = 1; + } + +#if OPENSSL_VERSION_NUMBER < 0x10100000L + SSL_CTX* ctx = SSL_CTX_new(SSLv23_method()); +#else + SSL_CTX* ctx = SSL_CTX_new(TLS_method()); +#endif + if (ctx == NULL) return NULL; + int mode = SSL_VERIFY_NONE; + const char* ca_file = NULL; + const char* ca_path = NULL; + if (param) { + if (param->ca_file && *param->ca_file) { + ca_file = param->ca_file; + } + if (param->ca_path && *param->ca_path) { + ca_path = param->ca_path; + } + if (ca_file || ca_path) { + if (!SSL_CTX_load_verify_locations(ctx, ca_file, ca_path)) { + fprintf(stderr, "ssl ca_file/ca_path failed!\n"); + goto error; + } + } + + if (param->crt_file && *param->crt_file) { + if (!SSL_CTX_use_certificate_file(ctx, param->crt_file, SSL_FILETYPE_PEM)) { + fprintf(stderr, "ssl crt_file error!\n"); + goto error; + } + } + + if (param->key_file && *param->key_file) { + if (!SSL_CTX_use_PrivateKey_file(ctx, param->key_file, SSL_FILETYPE_PEM)) { + fprintf(stderr, "ssl key_file error!\n"); + goto error; + } + if (!SSL_CTX_check_private_key(ctx)) { + fprintf(stderr, "ssl key_file check failed!\n"); + goto error; + } + } + + if (param->verify_peer) { + mode = SSL_VERIFY_PEER; + if (param->endpoint == HSSL_SERVER) { + mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + } + } + } + if (mode == SSL_VERIFY_PEER && !ca_file && !ca_path) { + SSL_CTX_set_default_verify_paths(ctx); + } + +#ifdef SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER + SSL_CTX_set_mode(ctx, SSL_CTX_get_mode(ctx) | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); +#endif + SSL_CTX_set_verify(ctx, mode, NULL); + return ctx; +error: + SSL_CTX_free(ctx); + return NULL; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) { + if (!ssl_ctx) return; + SSL_CTX_free((SSL_CTX*)ssl_ctx); +} + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) { + SSL* ssl = SSL_new((SSL_CTX*)ssl_ctx); + if (ssl == NULL) return NULL; + SSL_set_fd(ssl, fd); + return ssl; +} + +void hssl_free(hssl_t ssl) { + if (ssl) { + SSL_free((SSL*)ssl); + ssl = NULL; + } +} + +int hssl_accept(hssl_t ssl) { + int ret = SSL_accept((SSL*)ssl); + if (ret == 1) return 0; + + int err = SSL_get_error((SSL*)ssl, ret); + if (err == SSL_ERROR_WANT_READ) { + return HSSL_WANT_READ; + } + else if (err == SSL_ERROR_WANT_WRITE) { + return HSSL_WANT_WRITE; + } + return err; +} + +int hssl_connect(hssl_t ssl) { + int ret = SSL_connect((SSL*)ssl); + if (ret == 1) return 0; + + int err = SSL_get_error((SSL*)ssl, ret); + if (err == SSL_ERROR_WANT_READ) { + return HSSL_WANT_READ; + } + else if (err == SSL_ERROR_WANT_WRITE) { + return HSSL_WANT_WRITE; + } + return err; +} + +int hssl_read(hssl_t ssl, void* buf, int len) { + return SSL_read((SSL*)ssl, buf, len); +} + +int hssl_write(hssl_t ssl, const void* buf, int len) { + return SSL_write((SSL*)ssl, buf, len); +} + +int hssl_close(hssl_t ssl) { + SSL_shutdown((SSL*)ssl); + return 0; +} + +int hssl_set_sni_hostname(hssl_t ssl, const char* hostname) { +#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME + SSL_set_tlsext_host_name((SSL*)ssl, hostname); +#endif + return 0; +} + +#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation +static int hssl_ctx_alpn_select_cb(SSL *ssl, + const unsigned char **out, unsigned char *outlen, + const unsigned char *in, unsigned int inlen, + void *arg) { + const unsigned char* protos = (unsigned char*)arg; + unsigned int protos_len = strlen((char*)protos); + // printf("hssl_ctx_alpn_select_cb(in=%*.s:%u out=%.*s:%u protos=%.*s:%u)\n", inlen, in, inlen, (int)*outlen, (char*)out, (int)*outlen, protos_len, protos, protos_len); + if (SSL_select_next_proto((unsigned char **) out, outlen, protos, protos_len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { + fprintf(stderr, "SSL_select_next_proto failed!\n"); + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + // printf("SSL_select_next_proto(out=%.*s:%u)\n", (int)*outlen, (char*)*out, (int)*outlen); + return SSL_TLSEXT_ERR_OK; +} +#endif + +int hssl_ctx_set_alpn_protos(hssl_ctx_t ssl_ctx, const unsigned char* protos, unsigned int protos_len) { + int ret = -1; + // printf("hssl_ctx_set_alpn_protos(%.*s:%u)\n", protos_len, protos, protos_len); +#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation + // for HSSL_CLIENT + // ret = SSL_CTX_set_alpn_protos((SSL_CTX*)ssl_ctx, (const unsigned char*)protos, protos_len); + + // for HSSL_SERVER + SSL_CTX_set_alpn_select_cb((SSL_CTX*)ssl_ctx, hssl_ctx_alpn_select_cb, (void*)protos); + ret = 0; +#endif + return ret; +} + +#endif // WITH_OPENSSL diff --git a/external/libhv/libhv-1.3.2/ssl/wintls.c b/external/libhv/libhv-1.3.2/ssl/wintls.c new file mode 100644 index 0000000..98d056f --- /dev/null +++ b/external/libhv/libhv-1.3.2/ssl/wintls.c @@ -0,0 +1,837 @@ +#include "hssl.h" + +#ifdef WITH_WINTLS + +// #define PRINT_DEBUG +// #define PRINT_ERROR +#include "hdef.h" +#include +#include +#include +#include + +#define SECURITY_WIN32 +#include +#include + +#define TLS_SOCKET_BUFFER_SIZE 17000 + +#ifndef SP_PROT_SSL2_SERVER +#define SP_PROT_SSL2_SERVER 0x00000004 +#endif + +#ifndef SP_PROT_SSL2_CLIENT +#define SP_PROT_SSL2_CLIENT 0x00000008 +#endif + +#ifndef SP_PROT_SSL3_SERVER +#define SP_PROT_SSL3_SERVER 0x00000010 +#endif + +#ifndef SP_PROT_SSL3_CLIENT +#define SP_PROT_SSL3_CLIENT 0x00000020 +#endif + +#ifndef SP_PROT_TLS1_SERVER +#define SP_PROT_TLS1_SERVER 0x00000040 +#endif + +#ifndef SP_PROT_TLS1_CLIENT +#define SP_PROT_TLS1_CLIENT 0x00000080 +#endif + +#ifndef SP_PROT_TLS1_0_SERVER +#define SP_PROT_TLS1_0_SERVER SP_PROT_TLS1_SERVER +#endif + +#ifndef SP_PROT_TLS1_0_CLIENT +#define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT +#endif + +#ifndef SP_PROT_TLS1_1_SERVER +#define SP_PROT_TLS1_1_SERVER 0x00000100 +#endif + +#ifndef SP_PROT_TLS1_1_CLIENT +#define SP_PROT_TLS1_1_CLIENT 0x00000200 +#endif + +#ifndef SP_PROT_TLS1_2_SERVER +#define SP_PROT_TLS1_2_SERVER 0x00000400 +#endif + +#ifndef SP_PROT_TLS1_2_CLIENT +#define SP_PROT_TLS1_2_CLIENT 0x00000800 +#endif + +#ifndef SP_PROT_TLS1_3_SERVER +#define SP_PROT_TLS1_3_SERVER 0x00001000 +#endif + +#ifndef SP_PROT_TLS1_3_CLIENT +#define SP_PROT_TLS1_3_CLIENT 0x00002000 +#endif + +#ifndef SCH_USE_STRONG_CRYPTO +#define SCH_USE_STRONG_CRYPTO 0x00400000 +#endif + +#ifndef SECBUFFER_ALERT +#define SECBUFFER_ALERT 17 +#endif + +const char* hssl_backend() +{ + return "schannel"; +} + +static PCCERT_CONTEXT getservercert(const char* path) +{ + /* + According to the information I searched from the internet, it is not possible to specify an x509 private key and certificate using the + CertCreateCertificateContext interface. We must first export them as a pkcs#12 formatted file, and then import them into the Windows certificate store. This + is because the Windows certificate store is an integrated system location that does not support the direct use of separate private key files and certificate + files. The pkcs#12 format is a complex format that can store and protect keys and certificates. You can use the OpenSSL tool to combine the private key file + and certificate file into a pkcs#12 formatted file, For example: OpenSSL pkcs12 -export -out cert.pfx -inkey private.key -in cert.cer Then, you can use the + certutil tool or a graphical interface to import this file into the personal store of your local computer. After importing, you can use the + CertFindCertificateInStore interface to create and manipulate certificate contexts. + */ + return NULL; +} + +hssl_ctx_t hssl_ctx_new(hssl_ctx_opt_t* opt) +{ + SECURITY_STATUS SecStatus; + TimeStamp Lifetime; + CredHandle* hCred = NULL; + SCHANNEL_CRED credData = { 0 }; + TCHAR unisp_name[] = UNISP_NAME; + unsigned long credflag; + + if (opt && opt->endpoint == HSSL_SERVER) { + PCCERT_CONTEXT serverCert = NULL; // server-side certificate +#if 1 // create cert from store + + //------------------------------------------------------- + // Get the server certificate. + //------------------------------------------------------- + // Open the My store(personal store). + HCERTSTORE hMyCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING, 0, CERT_SYSTEM_STORE_LOCAL_MACHINE, L"MY"); + if (hMyCertStore == NULL) { + printe("Error opening MY store for server.\n"); + return NULL; + } + //------------------------------------------------------- + // Search for a certificate match its subject string to opt->crt_file. + serverCert = CertFindCertificateInStore(hMyCertStore, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR_A, opt->crt_file, NULL); + CertCloseStore(hMyCertStore, 0); + if (serverCert == NULL) { + printe("Error retrieving server certificate. %x\n", GetLastError()); + return NULL; + } +#else + serverCert = getservercert(opt->ca_file); +#endif + credData.cCreds = 1; // 数量 + credData.paCred = &serverCert; + // credData.dwCredFormat = SCH_CRED_FORMAT_CERT_HASH; + credData.grbitEnabledProtocols = SP_PROT_TLS1_2_SERVER | SP_PROT_TLS1_3_SERVER; + credflag = SECPKG_CRED_INBOUND; + } else { + credData.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT | SP_PROT_TLS1_3_CLIENT; + credflag = SECPKG_CRED_OUTBOUND; + } +#if 0 // just use the system defalut algs + ALG_ID rgbSupportedAlgs[4]; + rgbSupportedAlgs[0] = CALG_DH_EPHEM; + rgbSupportedAlgs[1] = CALG_RSA_KEYX; + rgbSupportedAlgs[2] = CALG_AES_128; + rgbSupportedAlgs[3] = CALG_SHA_256; + credData.cSupportedAlgs = 4; + credData.palgSupportedAlgs = rgbSupportedAlgs; +#endif + credData.dwVersion = SCHANNEL_CRED_VERSION; + // credData.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_NO_SERVERNAME_CHECK | SCH_USE_STRONG_CRYPTO | SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_IGNORE_NO_REVOCATION_CHECK | SCH_CRED_IGNORE_REVOCATION_OFFLINE; + // credData.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION | SCH_CRED_REVOCATION_CHECK_CHAIN | SCH_CRED_IGNORE_REVOCATION_OFFLINE; + // credData.dwMinimumCipherStrength = -1; + // credData.dwMaximumCipherStrength = -1; + + //------------------------------------------------------- + hCred = (CredHandle*)malloc(sizeof(CredHandle)); + if (hCred == NULL) { + return NULL; + } + + SecStatus = AcquireCredentialsHandle(NULL, unisp_name, credflag, NULL, &credData, NULL, NULL, hCred, &Lifetime); + if (SecStatus == SEC_E_OK) { +#ifndef NDEBUG + SecPkgCred_SupportedAlgs algs; + if (QueryCredentialsAttributesA(hCred, SECPKG_ATTR_SUPPORTED_ALGS, &algs) == SEC_E_OK) { + for (int i = 0; i < algs.cSupportedAlgs; i++) { + printd("alg: 0x%08x\n", algs.palgSupportedAlgs[i]); + } + } +#endif + } else { + printe("ERROR: AcquireCredentialsHandle: 0x%x\n", SecStatus); + free(hCred); + hCred = NULL; + } + return hCred; +} + +void hssl_ctx_free(hssl_ctx_t ssl_ctx) +{ + SECURITY_STATUS sec_status = FreeCredentialsHandle(ssl_ctx); + if (sec_status != SEC_E_OK) { + printe("free_cred_handle FreeCredentialsHandle %d\n", sec_status); + } +} + +static void init_sec_buffer(SecBuffer* secure_buffer, unsigned long type, unsigned long len, void* buffer) +{ + secure_buffer->BufferType = type; + secure_buffer->cbBuffer = len; + secure_buffer->pvBuffer = buffer; +} + +static void init_sec_buffer_desc(SecBufferDesc* secure_buffer_desc, unsigned long version, unsigned long num_buffers, SecBuffer* buffers) +{ + secure_buffer_desc->ulVersion = version; + secure_buffer_desc->cBuffers = num_buffers; + secure_buffer_desc->pBuffers = buffers; +} + +/* enum for the nonblocking SSL connection state machine */ +typedef enum { + ssl_connect_1, + ssl_connect_2, + ssl_connect_2_reading, + ssl_connect_2_writing, + ssl_connect_3, + ssl_connect_done +} ssl_connect_state; + +struct wintls_s { + hssl_ctx_t ssl_ctx; // CredHandle + int fd; + union { + ssl_connect_state state2; + ssl_connect_state connecting_state; + }; + SecHandle sechandle; + SecPkgContext_StreamSizes stream_sizes_; + size_t buffer_to_decrypt_offset_; + size_t dec_len_; + char encrypted_buffer_[TLS_SOCKET_BUFFER_SIZE]; + char buffer_to_decrypt_[TLS_SOCKET_BUFFER_SIZE]; + char decrypted_buffer_[TLS_SOCKET_BUFFER_SIZE + TLS_SOCKET_BUFFER_SIZE]; + char* sni; +}; + +hssl_t hssl_new(hssl_ctx_t ssl_ctx, int fd) +{ + struct wintls_s* ret = malloc(sizeof(*ret)); + if (ret) { + memset(ret, 0, sizeof(*ret)); + ret->ssl_ctx = ssl_ctx; + ret->fd = fd; + ret->sechandle.dwLower = 0; + ret->sechandle.dwUpper = 0; + } + return ret; +} + +void hssl_free(hssl_t _ssl) +{ + struct wintls_s* ssl = _ssl; + SECURITY_STATUS sec_status = DeleteSecurityContext(&ssl->sechandle); + if (sec_status != SEC_E_OK) { + printe("hssl_free DeleteSecurityContext %d", sec_status); + } + if (ssl->sni) { + free(ssl->sni); + } + free(ssl); +} + +static void free_all_buffers(SecBufferDesc* secure_buffer_desc) +{ + for (unsigned long i = 0; i < secure_buffer_desc->cBuffers; ++i) { + void* buffer = secure_buffer_desc->pBuffers[i].pvBuffer; + if (buffer != NULL) { + FreeContextBuffer(buffer); + } + } +} + +static int __sendwrapper(SOCKET fd, const char* buf, size_t len, int flags) +{ + int left = len; + int offset = 0; + while (left > 0) { + int bytes_sent = send(fd, buf + offset, left, flags); + if (bytes_sent == 0 || (bytes_sent == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK && WSAGetLastError() != WSAEINTR)) { + break; + } + if (bytes_sent > 0) { + offset += bytes_sent; + left -= bytes_sent; + } + } + return offset; +} + +static int __recvwrapper(SOCKET fd, char* buf, int len, int flags) +{ + int ret = 0; + do { + ret = recv(fd, buf, len, flags); + } while (ret == SOCKET_ERROR && WSAGetLastError() == WSAEINTR); + return ret; +} + +int hssl_accept(hssl_t ssl) +{ + int ret = HSSL_ERROR; + struct wintls_s* winssl = ssl; + bool authn_completed = false; + + // Input buffer + char buffer_in[TLS_SOCKET_BUFFER_SIZE]; + + SecBuffer secure_buffer_in[2] = { 0 }; + init_sec_buffer(&secure_buffer_in[0], SECBUFFER_TOKEN, TLS_SOCKET_BUFFER_SIZE, buffer_in); + init_sec_buffer(&secure_buffer_in[1], SECBUFFER_EMPTY, 0, NULL); + + SecBufferDesc secure_buffer_desc_in = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc_in, SECBUFFER_VERSION, 2, secure_buffer_in); + + // Output buffer + SecBuffer secure_buffer_out[3] = { 0 }; + init_sec_buffer(&secure_buffer_out[0], SECBUFFER_TOKEN, 0, NULL); + init_sec_buffer(&secure_buffer_out[1], SECBUFFER_ALERT, 0, NULL); + init_sec_buffer(&secure_buffer_out[2], SECBUFFER_EMPTY, 0, NULL); + + SecBufferDesc secure_buffer_desc_out = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 3, secure_buffer_out); + + unsigned long context_requirements = ASC_REQ_ALLOCATE_MEMORY | ASC_REQ_CONFIDENTIALITY; + + // We use ASC_REQ_ALLOCATE_MEMORY which means the buffers will be allocated for us, we need to make sure we free them. + + ULONG context_attributes = 0; + TimeStamp life_time = { 0 }; + + secure_buffer_in[0].cbBuffer = __recvwrapper(winssl->fd, (char*)secure_buffer_in[0].pvBuffer, TLS_SOCKET_BUFFER_SIZE, 0); + // printd("%s recv %d %d\n", __func__, secure_buffer_in[0].cbBuffer, WSAGetLastError()); + if (secure_buffer_in[0].cbBuffer == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) { + ret = HSSL_WANT_READ; + } else if (secure_buffer_in[0].cbBuffer > 0) { + SECURITY_STATUS sec_status = AcceptSecurityContext(winssl->ssl_ctx, winssl->state2 == 0 ? NULL : &winssl->sechandle, &secure_buffer_desc_in, + context_requirements, 0, &winssl->sechandle, &secure_buffer_desc_out, &context_attributes, &life_time); + + winssl->state2 = 1; + // printd("establish_server_security_context AcceptSecurityContext %x\n", sec_status); + + if (secure_buffer_out[0].cbBuffer > 0) { + int rc = __sendwrapper(winssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); + if (rc != secure_buffer_out[0].cbBuffer) { + goto END; + } + } + + switch (sec_status) { + case SEC_E_OK: + ret = HSSL_OK; + authn_completed = true; + break; + case SEC_I_CONTINUE_NEEDED: + ret = HSSL_WANT_READ; + break; + case SEC_I_COMPLETE_AND_CONTINUE: + case SEC_I_COMPLETE_NEEDED: { + SECURITY_STATUS complete_sec_status = SEC_E_OK; + complete_sec_status = CompleteAuthToken(&winssl->sechandle, &secure_buffer_desc_out); + if (complete_sec_status != SEC_E_OK) { + printe("establish_server_security_context CompleteAuthToken %x\n", complete_sec_status); + goto END; + } + + if (sec_status == SEC_I_COMPLETE_NEEDED) { + authn_completed = true; + ret = HSSL_OK; + } else { + ret = HSSL_WANT_READ; + } + break; + } + default: + break; + } + } +END: + free_all_buffers(&secure_buffer_desc_out); + + if (authn_completed) { + SECURITY_STATUS sec_status = QueryContextAttributes(&winssl->sechandle, SECPKG_ATTR_STREAM_SIZES, &winssl->stream_sizes_); + if (sec_status != SEC_E_OK) { + printe("get_stream_sizes QueryContextAttributes %d\n", sec_status); + } + } + return ret; +} + +static int schannel_connect_step1(struct wintls_s* ssl) +{ + int ret = 0; + ULONG context_attributes = 0; + unsigned long context_requirements = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; + + TimeStamp life_time = { 0 }; + + SecBuffer secure_buffer_out[1] = { 0 }; + init_sec_buffer(&secure_buffer_out[0], SECBUFFER_EMPTY, 0, NULL); + + SecBufferDesc secure_buffer_desc_out = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 1, secure_buffer_out); + + SECURITY_STATUS sec_status = InitializeSecurityContext(ssl->ssl_ctx, NULL, ssl->sni, context_requirements, 0, 0, NULL, 0, &ssl->sechandle, + &secure_buffer_desc_out, &context_attributes, &life_time); + + if (sec_status != SEC_I_CONTINUE_NEEDED) { + printe("1InitializeSecurityContext: %x\n", sec_status); + } + + if (secure_buffer_out[0].cbBuffer > 0) { + int rc = __sendwrapper(ssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); + if (rc != secure_buffer_out[0].cbBuffer) { + // TODO: Handle the error + printe("%s :send failed\n", __func__); + ret = -1; + } else { + printd("%s :send len=%d\n", __func__, rc); + ssl->connecting_state = ssl_connect_2; + } + } + free_all_buffers(&secure_buffer_desc_out); + return ret; +} + +static int schannel_connect_step2(struct wintls_s* ssl) +{ + int ret = HSSL_ERROR; + ULONG context_attributes = 0; + bool verify_server_cert = 0; + + unsigned long context_requirements = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM; + if (!verify_server_cert) { + context_requirements |= ISC_REQ_MANUAL_CRED_VALIDATION; + } + + TimeStamp life_time = { 0 }; + + // Allocate a temporary buffer for input + char* buffer_in = malloc(TLS_SOCKET_BUFFER_SIZE); + if (buffer_in == NULL) { + printe("schannel_connect_step2: Memory allocation failed\n"); + return HSSL_ERROR; + } + + int offset = 0; + bool skip_recv = false; + bool authn_complete = false; + while (!authn_complete) { + int in_buffer_size = 0; + + if (!skip_recv) { + int received = __recvwrapper(ssl->fd, buffer_in + offset, TLS_SOCKET_BUFFER_SIZE, 0); + if (received == SOCKET_ERROR) { + if (WSAGetLastError() == WSAEWOULDBLOCK) { + ret = HSSL_WANT_READ; + } else { + printe("schannel_connect_step2: Receive failed\n"); + } + break; + } else if (received == 0) { + printe("schannel_connect_step2: peer closed\n"); + break; + } + in_buffer_size = received + offset; + } else { + in_buffer_size = offset; + } + + skip_recv = false; + offset = 0; + + // Input buffer + SecBuffer secure_buffer_in[4] = { 0 }; + init_sec_buffer(&secure_buffer_in[0], SECBUFFER_TOKEN, in_buffer_size, buffer_in); + init_sec_buffer(&secure_buffer_in[1], SECBUFFER_EMPTY, 0, NULL); + + SecBufferDesc secure_buffer_desc_in = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc_in, SECBUFFER_VERSION, 2, secure_buffer_in); + + // Output buffer + SecBuffer secure_buffer_out[3] = { 0 }; + init_sec_buffer(&secure_buffer_out[0], SECBUFFER_TOKEN, 0, NULL); + init_sec_buffer(&secure_buffer_out[1], SECBUFFER_ALERT, 0, NULL); + init_sec_buffer(&secure_buffer_out[2], SECBUFFER_EMPTY, 0, NULL); + + SecBufferDesc secure_buffer_desc_out = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc_out, SECBUFFER_VERSION, 3, secure_buffer_out); + printd("h2:%d\n", in_buffer_size); + SECURITY_STATUS sec_status = InitializeSecurityContext(ssl->ssl_ctx, &ssl->sechandle, ssl->sni, context_requirements, 0, 0, &secure_buffer_desc_in, 0, + &ssl->sechandle, &secure_buffer_desc_out, &context_attributes, &life_time); + + printd("h2 0x%x inbuf[1] type=%d %d inbuf[0]=%d\n", sec_status, secure_buffer_in[1].BufferType, secure_buffer_in[1].cbBuffer, secure_buffer_in[0].cbBuffer); + if (sec_status == SEC_E_OK || sec_status == SEC_I_CONTINUE_NEEDED) { + // for (size_t i = 0; i < 3; i++) { + // printd("obuf[%zu] type=%d %d\n", i, secure_buffer_out[i].BufferType, secure_buffer_out[i].cbBuffer); + // } + if (secure_buffer_out[0].cbBuffer > 0) { + int rc = __sendwrapper(ssl->fd, (const char*)secure_buffer_out[0].pvBuffer, secure_buffer_out[0].cbBuffer, 0); + if (rc != secure_buffer_out[0].cbBuffer) { + printe("schannel_connect_step2: Send failed\n"); + // TODO: Handle the error + break; + } + // printd("%s :send ok\n", __func__); + } + + if (sec_status == SEC_I_CONTINUE_NEEDED) { + if (secure_buffer_in[1].BufferType == SECBUFFER_EXTRA && secure_buffer_in[1].cbBuffer > 0) { + offset = secure_buffer_in[0].cbBuffer - secure_buffer_in[1].cbBuffer; + memmove(buffer_in, buffer_in + offset, secure_buffer_in[1].cbBuffer); + offset = secure_buffer_in[1].cbBuffer; + skip_recv = true; + } + } else if (sec_status == SEC_E_OK) { + authn_complete = true; + ret = HSSL_OK; + ssl->connecting_state = ssl_connect_3; + } + } else if (sec_status == SEC_E_INCOMPLETE_MESSAGE) { + offset = secure_buffer_in[0].cbBuffer; + } else { + printe("2InitializeSecurityContext: 0x%x\n", sec_status); + break; + } + + free_all_buffers(&secure_buffer_desc_out); + } + // END: + free(buffer_in); // Free the temporary buffer + return ret; +} + +static void dumpconninfo(SecHandle* sechandle) +{ + SECURITY_STATUS Status; + SecPkgContext_ConnectionInfo ConnectionInfo; + + Status = QueryContextAttributes(sechandle, + SECPKG_ATTR_CONNECTION_INFO, + (PVOID)&ConnectionInfo); + if (Status != SEC_E_OK) { + printe("Error 0x%x querying connection info\n", Status); + return; + } + + printd("\n"); + + switch (ConnectionInfo.dwProtocol) { + case SP_PROT_TLS1_CLIENT: + printd("Protocol: TLS1\n"); + break; + + case SP_PROT_SSL3_CLIENT: + printd("Protocol: SSL3\n"); + break; + + case SP_PROT_SSL2_CLIENT: + printd("Protocol: SSL2\n"); + break; + + case SP_PROT_PCT1_CLIENT: + printd("Protocol: PCT\n"); + break; + + default: + printd("Protocol: 0x%x\n", ConnectionInfo.dwProtocol); + } + + switch (ConnectionInfo.aiCipher) { + case CALG_RC4: + printd("Cipher: RC4\n"); + break; + + case CALG_3DES: + printd("Cipher: Triple DES\n"); + break; + + case CALG_RC2: + printd("Cipher: RC2\n"); + break; + + case CALG_DES: + case CALG_CYLINK_MEK: + printd("Cipher: DES\n"); + break; + + case CALG_SKIPJACK: + printd("Cipher: Skipjack\n"); + break; + + case CALG_AES_128: + printd("Cipher: aes128\n"); + break; + default: + printd("Cipher: 0x%x\n", ConnectionInfo.aiCipher); + } + + printd("Cipher strength: %d\n", ConnectionInfo.dwCipherStrength); + + switch (ConnectionInfo.aiHash) { + case CALG_MD5: + printd("Hash: MD5\n"); + break; + + case CALG_SHA: + printd("Hash: SHA\n"); + break; + + default: + printd("Hash: 0x%x\n", ConnectionInfo.aiHash); + } + + printd("Hash strength: %d\n", ConnectionInfo.dwHashStrength); + + switch (ConnectionInfo.aiExch) { + case CALG_RSA_KEYX: + case CALG_RSA_SIGN: + printd("Key exchange: RSA\n"); + break; + + case CALG_KEA_KEYX: + printd("Key exchange: KEA\n"); + break; + + case CALG_DH_EPHEM: + printd("Key exchange: DH Ephemeral\n"); + break; + + default: + printd("Key exchange: 0x%x\n", ConnectionInfo.aiExch); + } + + printd("Key exchange strength: %d\n", ConnectionInfo.dwExchStrength); +} + +int hssl_connect(hssl_t _ssl) +{ + int ret = 0; + struct wintls_s* ssl = _ssl; + if (ssl->connecting_state == ssl_connect_1) { + ret = schannel_connect_step1(ssl); + } + if (!ret && ssl->connecting_state == ssl_connect_2) { + ret = schannel_connect_step2(ssl); + } + // printd("%s %x\n", __func__, ret); + if (!ret) { + if (ssl->connecting_state == ssl_connect_3) { + // ret = schannel_connect_step3(ssl); + } + SECURITY_STATUS sec_status = QueryContextAttributes(&ssl->sechandle, SECPKG_ATTR_STREAM_SIZES, &ssl->stream_sizes_); + if (sec_status != SEC_E_OK) { + printe("get_stream_sizes QueryContextAttributes %d\n", sec_status); + } else { + printd("stream_sizes bs:%d h:%d t:%d max:%d bfs:%d\n", ssl->stream_sizes_.cbBlockSize, ssl->stream_sizes_.cbHeader, ssl->stream_sizes_.cbTrailer, ssl->stream_sizes_.cbMaximumMessage, ssl->stream_sizes_.cBuffers); + } + dumpconninfo(&ssl->sechandle); + } + return ret; +} + +static int decrypt_message(SecHandle security_context, unsigned long* extra, char* in_buf, int in_len, char* out_buf, int out_len) +{ + printd("%s: inlen=%d\n", __func__, in_len); + // Initialize the secure buffers + SecBuffer secure_buffers[4] = { 0 }; + init_sec_buffer(&secure_buffers[0], SECBUFFER_DATA, in_len, in_buf); + init_sec_buffer(&secure_buffers[1], SECBUFFER_EMPTY, 0, NULL); + init_sec_buffer(&secure_buffers[2], SECBUFFER_EMPTY, 0, NULL); + init_sec_buffer(&secure_buffers[3], SECBUFFER_EMPTY, 0, NULL); + + // Initialize the secure buffer descriptor + SecBufferDesc secure_buffer_desc = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc, SECBUFFER_VERSION, 4, secure_buffers); + + // Decrypt the message using the security context + SECURITY_STATUS sec_status = DecryptMessage(&security_context, &secure_buffer_desc, 0, NULL); + + for (size_t i = 1; i < 4; i++) { + printd("%d: %u %u\n", i, secure_buffers[i].BufferType, secure_buffers[i].cbBuffer); + } + if (sec_status == SEC_E_INCOMPLETE_MESSAGE) { + printe("decrypt_message SEC_E_INCOMPLETE_MESSAGE\n"); + return -1; + } else if (sec_status == SEC_E_DECRYPT_FAILURE) { + printe("decrypt_message ignore SEC_E_DECRYPT_FAILURE\n"); + return 0; + } else if (sec_status == SEC_E_UNSUPPORTED_FUNCTION) { + printe("decrypt_message ignore SEC_E_UNSUPPORTED_FUNCTION\n"); + return 0; + } + + if (sec_status != SEC_E_OK) { + printe("decrypt_message DecryptMessage: 0x%x\n", sec_status); + return -1; + } + if (secure_buffers[3].BufferType == SECBUFFER_EXTRA && secure_buffers[3].cbBuffer > 0) { + *extra = secure_buffers[3].cbBuffer; + } + memcpy(out_buf, secure_buffers[1].pvBuffer, secure_buffers[1].cbBuffer); + // printd("ob:%s\n", out_buf); + return secure_buffers[1].cbBuffer; +} + +int hssl_read(hssl_t _ssl, void* buf, int len) +{ + struct wintls_s* ssl = _ssl; + printd("%s: dec_len_= %zu\n", __func__, ssl->dec_len_); + if (ssl->dec_len_ > 0) { + if (buf == NULL) { + return 0; + } + int decrypted = MIN(ssl->dec_len_, len); + memcpy(buf, ssl->decrypted_buffer_, (size_t)decrypted); + ssl->dec_len_ -= decrypted; + if (ssl->dec_len_) { + memmove(ssl->decrypted_buffer_, ssl->decrypted_buffer_ + decrypted, (size_t)ssl->dec_len_); + } else { + // hssl_read(_ssl, NULL, 0); + } + return decrypted; + } + + // We might have leftovers, an incomplete message from a previous call. + // Calculate the available buffer length for tcp recv. + int recv_max_len = TLS_SOCKET_BUFFER_SIZE - ssl->buffer_to_decrypt_offset_; + int bytes_received = __recvwrapper(ssl->fd, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, recv_max_len, 0); + // printd("%s recv %d %d\n", __func__, bytes_received, WSAGetLastError()); + if (bytes_received == SOCKET_ERROR) { + if (WSAGetLastError() == WSAEWOULDBLOCK) { + bytes_received = 0; + return 0; + } else { + return -1; + } + } else if (bytes_received == 0) { + return 0; + } + + int encrypted_buffer_len = ssl->buffer_to_decrypt_offset_ + bytes_received; + ssl->buffer_to_decrypt_offset_ = 0; + while (true) { + // printd("%s:buffer_to_decrypt_offset_ = %d , encrypted_buffer_len= %d\n", __func__, ssl->buffer_to_decrypt_offset_, encrypted_buffer_len); + if (ssl->buffer_to_decrypt_offset_ >= encrypted_buffer_len) { + // Reached the encrypted buffer length, we decrypted everything so we can stop. + break; + } + unsigned long extra = 0; + int decrypted_len = decrypt_message(ssl->sechandle, &extra, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, + encrypted_buffer_len - ssl->buffer_to_decrypt_offset_, ssl->decrypted_buffer_ + ssl->dec_len_, + TLS_SOCKET_BUFFER_SIZE + TLS_SOCKET_BUFFER_SIZE - ssl->dec_len_); + + if (decrypted_len == -1) { + // Incomplete message, we shuold keep it so it will be decrypted on the next call to recv(). + // Shift the remaining buffer to the beginning and break the loop. + + memmove(ssl->buffer_to_decrypt_, ssl->buffer_to_decrypt_ + ssl->buffer_to_decrypt_offset_, encrypted_buffer_len - ssl->buffer_to_decrypt_offset_); + + break; + } + + ssl->dec_len_ += decrypted_len; + ssl->buffer_to_decrypt_offset_ = encrypted_buffer_len - extra; + } + ssl->buffer_to_decrypt_offset_ = encrypted_buffer_len - ssl->buffer_to_decrypt_offset_; + return hssl_read(_ssl, buf, len); +} + +int hssl_write(hssl_t _ssl, const void* buf, int len) +{ + struct wintls_s* ssl = _ssl; + SecPkgContext_StreamSizes* stream_sizes = &ssl->stream_sizes_; + if (len > (int)stream_sizes->cbMaximumMessage) { + len = stream_sizes->cbMaximumMessage; + } + + // Calculate the minimum output buffer length + int min_out_len = stream_sizes->cbHeader + len + stream_sizes->cbTrailer; + if (min_out_len > TLS_SOCKET_BUFFER_SIZE) { + printe("encrypt_message: Output buffer is too small"); + return -1; + } + + // Initialize the secure buffers + SecBuffer secure_buffers[4] = { 0 }; + init_sec_buffer(&secure_buffers[0], SECBUFFER_STREAM_HEADER, stream_sizes->cbHeader, ssl->encrypted_buffer_); + init_sec_buffer(&secure_buffers[1], SECBUFFER_DATA, len, ssl->encrypted_buffer_ + stream_sizes->cbHeader); + init_sec_buffer(&secure_buffers[2], SECBUFFER_STREAM_TRAILER, stream_sizes->cbTrailer, ssl->encrypted_buffer_ + stream_sizes->cbHeader + len); + init_sec_buffer(&secure_buffers[3], SECBUFFER_EMPTY, 0, NULL); + + // Initialize the secure buffer descriptor + SecBufferDesc secure_buffer_desc = { 0 }; + init_sec_buffer_desc(&secure_buffer_desc, SECBUFFER_VERSION, 4, secure_buffers); + + // Copy the input buffer to the data buffer + memcpy(secure_buffers[1].pvBuffer, buf, len); + + // Encrypt the message using the security context + SECURITY_STATUS sec_status = EncryptMessage(&ssl->sechandle, 0, &secure_buffer_desc, 0); + + // Check the encryption status and the data buffer length + if (sec_status != SEC_E_OK) { + printe("encrypt_message EncryptMessage %d\n", sec_status); + return -1; + } + if (secure_buffers[1].cbBuffer > (unsigned int)len) { + printe("encrypt_message: Data buffer is too large\n"); + return -1; + } + + // Adjust the minimum output buffer length + min_out_len = secure_buffers[0].cbBuffer + secure_buffers[1].cbBuffer + secure_buffers[2].cbBuffer; + printd("enc02: %d %d\n", secure_buffers[0].cbBuffer, secure_buffers[2].cbBuffer); + + // Send the encrypted message to the socket + int offset = __sendwrapper(ssl->fd, ssl->encrypted_buffer_, min_out_len, 0); + // Check the send result + if (offset != min_out_len) { + printe("hssl_write: Send failed\n"); + return -1; + } else { + printd("hssl_write: Send %d\n", min_out_len); + } + + // Return the number of bytes sent excluding the header and trailer + return offset - secure_buffers[0].cbBuffer - secure_buffers[2].cbBuffer; +} + +int hssl_close(hssl_t _ssl) +{ + return 0; +} + +int hssl_set_sni_hostname(hssl_t _ssl, const char* hostname) +{ + struct wintls_s* ssl = _ssl; + ssl->sni = strdup(hostname); + return 0; +} + +#endif // WITH_WINTLS diff --git a/external/libhv/libhv-1.3.2/unittest/CMakeLists.txt b/external/libhv/libhv-1.3.2/unittest/CMakeLists.txt new file mode 100644 index 0000000..4e469e6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/CMakeLists.txt @@ -0,0 +1,118 @@ +add_definitions(-DHV_SOURCE=1) + +# ------base------ +add_executable(hbase_test hbase_test.c ../base/hbase.c) +target_include_directories(hbase_test PRIVATE .. ../base) + +add_executable(mkdir_p mkdir_test.c ../base/hbase.c) +target_include_directories(mkdir_p PRIVATE .. ../base) + +add_executable(rmdir_p rmdir_test.c ../base/hbase.c) +target_include_directories(rmdir_p PRIVATE .. ../base) + +add_executable(date date_test.c ../base/htime.c) +target_include_directories(date PRIVATE .. ../base) + +add_executable(hatomic_test hatomic_test.c) +target_include_directories(hatomic_test PRIVATE .. ../base) +target_link_libraries(hatomic_test -lpthread) + +add_executable(hthread_test hthread_test.cpp) +target_include_directories(hthread_test PRIVATE .. ../base) +target_link_libraries(hthread_test -lpthread) + +add_executable(hmutex_test hmutex_test.c ../base/htime.c) +target_include_directories(hmutex_test PRIVATE .. ../base) +target_link_libraries(hmutex_test -lpthread) + +add_executable(connect_test connect_test.c ../base/hsocket.c ../base/htime.c) +target_include_directories(connect_test PRIVATE .. ../base) + +add_executable(socketpair_test socketpair_test.c ../base/hsocket.c) +target_include_directories(socketpair_test PRIVATE .. ../base) + +# ------util------ +add_executable(base64 base64_test.c ../util/base64.c) +target_include_directories(base64 PRIVATE .. ../util) + +add_executable(md5 md5_test.c ../util/md5.c) +target_include_directories(md5 PRIVATE .. ../util) + +add_executable(sha1 sha1_test.c ../util/sha1.c) +target_include_directories(sha1 PRIVATE .. ../util) + +# ------cpputil------ +add_executable(hstring_test hstring_test.cpp ../cpputil/hstring.cpp) +target_include_directories(hstring_test PRIVATE .. ../base ../cpputil) + +add_executable(hpath_test hpath_test.cpp ../cpputil/hpath.cpp) +target_include_directories(hpath_test PRIVATE .. ../base ../cpputil) + +add_executable(hurl_test hurl_test.cpp ../cpputil/hurl.cpp ../base/hbase.c) +target_include_directories(hurl_test PRIVATE .. ../base ../cpputil) + +add_executable(ls listdir_test.cpp ../cpputil/hdir.cpp) +target_include_directories(ls PRIVATE .. ../base ../cpputil) + +add_executable(ifconfig ifconfig_test.cpp ../cpputil/ifconfig.cpp) +target_include_directories(ifconfig PRIVATE .. ../base ../cpputil) + +add_executable(defer_test defer_test.cpp) +target_include_directories(defer_test PRIVATE .. ../base ../cpputil) + +add_executable(synchronized_test synchronized_test.cpp) +target_include_directories(synchronized_test PRIVATE .. ../base ../cpputil) +target_link_libraries(synchronized_test -lpthread) + +add_executable(threadpool_test threadpool_test.cpp) +target_include_directories(threadpool_test PRIVATE .. ../base ../cpputil) +target_link_libraries(threadpool_test -lpthread) + +add_executable(objectpool_test objectpool_test.cpp) +target_include_directories(objectpool_test PRIVATE .. ../base ../cpputil) +target_link_libraries(objectpool_test -lpthread) + +# ------protocol------ +add_executable(nslookup nslookup_test.c ../protocol/dns.c) +target_include_directories(nslookup PRIVATE .. ../base ../protocol) + +add_executable(ping ping_test.c ../protocol/icmp.c ../base/hsocket.c ../base/htime.c) +target_compile_definitions(ping PRIVATE -DPRINT_DEBUG) +target_include_directories(ping PRIVATE .. ../base ../protocol) + +add_executable(ftp ftp_test.c ../protocol/ftp.c ../base/hsocket.c) +target_include_directories(ftp PRIVATE .. ../base ../protocol) + +add_executable(sendmail sendmail_test.c ../protocol/smtp.c ../base/hsocket.c ../util/base64.c) +target_include_directories(sendmail PRIVATE .. ../base ../protocol ../util) + +if(UNIX) +add_executable(webbench webbench.c) +endif() + +add_custom_target(unittest DEPENDS + mkdir_p + rmdir_p + date + hatomic_test + hthread_test + hmutex_test + connect_test + socketpair_test + base64 + md5 + sha1 + hstring_test + hpath_test + hurl_test + ls + ifconfig + defer_test + synchronized_test + threadpool_test + objectpool_test + nslookup + ping + ftp + sendmail +) diff --git a/external/libhv/libhv-1.3.2/unittest/base64_test.c b/external/libhv/libhv-1.3.2/unittest/base64_test.c new file mode 100644 index 0000000..2574008 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/base64_test.c @@ -0,0 +1,118 @@ +/* + * @build: gcc -o bin/base64 unittest/base64_test.c util/base64.c -I. -Iutil + * + */ + +#include +#include +#include +#include + +#include "base64.h" + +static void test() { + unsigned char in[] = "0123456789"; + // test encode + int encoded_size = BASE64_ENCODE_OUT_SIZE(10); + char* encoded = (char*)malloc(encoded_size + 1); + encoded_size = hv_base64_encode(in, 10, encoded); + encoded[encoded_size] = '\0'; + assert(strcmp(encoded, "MDEyMzQ1Njc4OQ==") == 0); + // test decode + int decoded_size = BASE64_DECODE_OUT_SIZE(encoded_size); + unsigned char* decoded = (unsigned char*)malloc(decoded_size); + decoded_size = hv_base64_decode(encoded, encoded_size, decoded); + assert(decoded_size == 10 && memcmp(in, decoded, decoded_size) == 0); + + free(encoded); + free(decoded); +} + +int main(int argc, char* argv[]) { + test(); + + if (argc < 3) { + printf("Usage: base64 infile outfile\n"); + printf(" base64 -d infile outfile\n"); + return -10; + } + else if (argc == 3) { + // encode file + const char* infile = argv[1]; + const char* outfile = argv[2]; + + FILE* infp = fopen(infile, "rb"); + if (infp == NULL) { + printf("Open file '%s' failed!\n", infile); + return -20; + } + fseek(infp, 0, SEEK_END); + long filesize = ftell(infp); + // printf("filesize=%ld\n", filesize); + fseek(infp, 0, SEEK_SET); + unsigned char* filebuf = (unsigned char*)malloc(filesize); + size_t nread = fread(filebuf, 1, filesize, infp); + assert(nread == filesize); + + int encoded_size = BASE64_ENCODE_OUT_SIZE(filesize); + char* encoded = (char*)malloc(encoded_size + 1); + encoded_size = hv_base64_encode(filebuf, filesize, encoded); + encoded[encoded_size] = '\0'; + + FILE* outfp = fopen(outfile, "w"); + if (outfp == NULL) { + printf("Save file '%s' failed!\n", infile); + return -20; + } + size_t nwrite = fwrite(encoded, 1, encoded_size, outfp); + assert(nwrite == encoded_size); + + free(filebuf); + free(encoded); + fclose(infp); + fclose(outfp); + } + else if (argc == 4) { + const char* flags = argv[1]; + if (flags[0] == '-' && flags[1] == 'd') { + // decode file + const char* infile = argv[2]; + const char* outfile = argv[3]; + FILE* infp = fopen(infile, "r"); + if (infp == NULL) { + printf("Open file '%s' failed!\n", infile); + return -20; + } + fseek(infp, 0, SEEK_END); + long filesize = ftell(infp); + // printf("filesize=%ld\n", filesize); + fseek(infp, 0, SEEK_SET); + char* filebuf = (char*)malloc(filesize); + size_t nread = fread(filebuf, 1, filesize, infp); + assert(nread == filesize); + + int decoded_size = BASE64_DECODE_OUT_SIZE(filesize); + unsigned char* decoded = (unsigned char*)malloc(decoded_size); + decoded_size = hv_base64_decode(filebuf, filesize, decoded); + + FILE* outfp = fopen(outfile, "wb"); + if (outfp == NULL) { + printf("Save file '%s' failed!\n", infile); + return -20; + } + size_t nwrite = fwrite(decoded, 1, decoded_size, outfp); + assert(nwrite == decoded_size); + + free(filebuf); + free(decoded); + fclose(infp); + fclose(outfp); + } + else { + printf("Unrecognized flags '%s'\n", flags); + return -40; + } + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/connect_test.c b/external/libhv/libhv-1.3.2/unittest/connect_test.c new file mode 100644 index 0000000..9a1792e --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/connect_test.c @@ -0,0 +1,29 @@ +#include "hsocket.h" +#include "htime.h" + +int main(int argc, char* argv[]) { + if (argc < 3) { + printf("Usage: cmd ip port\n"); + return -10; + } + + const char* ip = argv[1]; + int port = atoi(argv[2]); + + unsigned int start_time = gettick_ms(); + int ret = ConnectNonblock(ip, port); + unsigned int end_time = gettick_ms(); + printf("ConnectNonblock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); + + start_time = gettick_ms(); + ret = ConnectTimeout(ip, port, 3000); + end_time = gettick_ms(); + printf("ConnectTimeout[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); + + start_time = gettick_ms(); + ret = Connect(ip, port, 0); + end_time = gettick_ms(); + printf("ConnectBlock[%s:%d] retval=%d cost=%ums\n", ip, port, ret, end_time-start_time); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/date_test.c b/external/libhv/libhv-1.3.2/unittest/date_test.c new file mode 100644 index 0000000..3a74398 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/date_test.c @@ -0,0 +1,17 @@ +#include "htime.h" + +int main(int argc, char* argv[]) { + datetime_t dt = datetime_now(); + char buf1[DATETIME_FMT_BUFLEN]; + datetime_fmt(&dt, buf1); + puts(buf1); + datetime_fmt_iso(&dt, buf1); + puts(buf1); + + time_t ts = datetime_mktime(&dt); + char buf2[GMTIME_FMT_BUFLEN]; + gmtime_fmt(ts, buf2); + puts(buf2); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/defer_test.cpp b/external/libhv/libhv-1.3.2/unittest/defer_test.cpp new file mode 100644 index 0000000..48d43ab --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/defer_test.cpp @@ -0,0 +1,19 @@ +#include + +#include "hscope.h" + +int main() { + defer ( + printf("1\n"); + printf("2\n"); + ) + + defer ( + printf("3\n"); + printf("4\n"); + ) + + defer(printf("hello\n");) + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/ftp_test.c b/external/libhv/libhv-1.3.2/unittest/ftp_test.c new file mode 100644 index 0000000..ec5dbca --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/ftp_test.c @@ -0,0 +1,88 @@ +#include +#include +#include + +#include "ftp.h" + +void print_help() { + printf("Usage:\n\ +help\n\ +login \n\ +download \n\ +upload \n\ +quit\n"); +} + +int main(int argc, char** argv) { + if (argc < 2) { + printf("Usage: ftp host [port]\n"); + return 0; + } + const char* host = argv[1]; + int port = FTP_COMMAND_PORT; + if (argc >= 3) { + port = atoi(argv[2]); + } + int ret = 0; + ftp_handle_t hftp; + ret = ftp_connect(&hftp, host, port); + if (ret != 0) { + printf("ftp connect failed!\n"); + return ret; + } + print_help(); + + char cmd[256] = {0}; + char param1[256] = {0}; + char param2[256] = {0}; + while (1) { + printf("> "); + scanf("%s", cmd); + if (strncmp(cmd, "help", 4) == 0) { + print_help(); + } + else if (strncmp(cmd, "login", 5) == 0) { + scanf("%s", param1); + scanf("%s", param2); + //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); + const char* username = param1; + const char* password = param2; + ret = ftp_login(&hftp, username, password); + printf("%s", hftp.recvbuf); + if (ret != 0) break; + } + else if (strncmp(cmd, "upload", 6) == 0) { + scanf("%s", param1); + scanf("%s", param2); + //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); + const char* localfile = param1; + const char* remotefile = param2; + ret = ftp_upload(&hftp, localfile, remotefile); + printf("%s", hftp.recvbuf); + if (ret != 0) break; + } + else if (strncmp(cmd, "download", 8) == 0) { + scanf("%s", param1); + scanf("%s", param2); + //printf("cmd=%s param1=%s param2=%s\n", cmd, param1, param2); + const char* remotefile = param1; + const char* localfile = param2; + ret = ftp_download(&hftp, remotefile, localfile); + printf("%s", hftp.recvbuf); + if (ret != 0) break; + } + else if (strncmp(cmd, "quit", 4) == 0) { + break; + } + else { + scanf("%s", param1); + //printf("cmd=%s param=%s\n", cmd, param1); + ret = ftp_exec(&hftp, cmd, param1); + printf("%s", hftp.recvbuf); + } + } + printf("QUIT\n"); + ftp_quit(&hftp); + printf("%s", hftp.recvbuf); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hatomic_test.c b/external/libhv/libhv-1.3.2/unittest/hatomic_test.c new file mode 100644 index 0000000..81f208b --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hatomic_test.c @@ -0,0 +1,39 @@ +#include + +#include "hatomic.h" +#include "hthread.h" + +hatomic_flag_t flag = HATOMIC_FLAG_INIT; +hatomic_t cnt = HATOMIC_VAR_INIT(0); + +HTHREAD_ROUTINE(test_hatomic_flag) { + if (!hatomic_flag_test_and_set(&flag)) { + printf("tid=%ld flag 0=>1\n", hv_gettid()); + } + else { + printf("tid=%ld flag=1\n", hv_gettid()); + } + return 0; +} + +HTHREAD_ROUTINE(test_hatomic) { + for (int i = 0; i < 10; ++i) { + long n = hatomic_inc(&cnt); + printf("tid=%ld cnt=%ld\n", hv_gettid(), n); + hv_delay(1); + } + return 0; +} + +int main() { + for (int i = 0; i < 10; ++i) { + hthread_create(test_hatomic_flag, NULL); + } + + for (int i = 0; i < 10; ++i) { + hthread_create(test_hatomic, NULL); + } + + hv_delay(1000); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hatomic_test.cpp b/external/libhv/libhv-1.3.2/unittest/hatomic_test.cpp new file mode 100644 index 0000000..81f208b --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hatomic_test.cpp @@ -0,0 +1,39 @@ +#include + +#include "hatomic.h" +#include "hthread.h" + +hatomic_flag_t flag = HATOMIC_FLAG_INIT; +hatomic_t cnt = HATOMIC_VAR_INIT(0); + +HTHREAD_ROUTINE(test_hatomic_flag) { + if (!hatomic_flag_test_and_set(&flag)) { + printf("tid=%ld flag 0=>1\n", hv_gettid()); + } + else { + printf("tid=%ld flag=1\n", hv_gettid()); + } + return 0; +} + +HTHREAD_ROUTINE(test_hatomic) { + for (int i = 0; i < 10; ++i) { + long n = hatomic_inc(&cnt); + printf("tid=%ld cnt=%ld\n", hv_gettid(), n); + hv_delay(1); + } + return 0; +} + +int main() { + for (int i = 0; i < 10; ++i) { + hthread_create(test_hatomic_flag, NULL); + } + + for (int i = 0; i < 10; ++i) { + hthread_create(test_hatomic, NULL); + } + + hv_delay(1000); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hbase_test.c b/external/libhv/libhv-1.3.2/unittest/hbase_test.c new file mode 100644 index 0000000..be6e726 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hbase_test.c @@ -0,0 +1,114 @@ +#include "hbase.h" + +int main(int argc, char* argv[]) { + char buf[16] = {0}; + printf("hv_rand(10, 99) -> %d\n", hv_rand(10, 99)); + printf("hv_random_string(buf, 10) -> %s\n", hv_random_string(buf, 10)); + + assert(hv_getboolean("1")); + assert(hv_getboolean("yes")); + + assert(hv_wildcard_match("www.example.com", "www.example.com")); + assert(hv_wildcard_match("www.example.com", "*.example.com")); + assert(hv_wildcard_match("www.example.com", "www.*.com")); + assert(hv_wildcard_match("www.example.com", "www.example.*")); + + assert(hv_parse_size("256") == 256); + assert(hv_parse_size("1K") == 1024); + assert(hv_parse_size("1G2M3K4B") == + 1 * 1024 * 1024 * 1024 + + 2 * 1024 * 1024 + + 3 * 1024 + + 4); + + assert(hv_parse_time("30") == 30); + assert(hv_parse_time("1m") == 60); + assert(hv_parse_time("1d2h3m4s") == + 1 * 24 * 60 * 60 + + 2 * 60 * 60 + + 3 * 60 + + 4); + + const char* test_urls[] = { + "http://user:pswd@www.example.com:80/path?query#fragment", + "http://user:pswd@www.example.com/path?query#fragment", + "http://www.example.com/path?query#fragment", + "http://www.example.com/path?query", + "http://www.example.com/path", + "www.example.com/path", + "/path", + }; + hurl_t stURL; + for (int i = 0; i < ARRAY_SIZE(test_urls); ++i) { + const char* strURL = test_urls[i]; + printf("%s =>\n", strURL); + hv_parse_url(&stURL, strURL); + assert(stURL.port == 80); + // scheme:// + if (stURL.fields[HV_URL_SCHEME].len > 0) { + const char* scheme = strURL + stURL.fields[HV_URL_SCHEME].off; + int len = stURL.fields[HV_URL_SCHEME].len; + assert(len == 4); + assert(strncmp(scheme, "http", len) == 0); + printf("%.*s://", len, scheme); + } + // user:pswd@ + if (stURL.fields[HV_URL_USERNAME].len > 0) { + const char* user = strURL + stURL.fields[HV_URL_USERNAME].off; + int len = stURL.fields[HV_URL_USERNAME].len; + assert(len == 4); + assert(strncmp(user, "user", len) == 0); + printf("%.*s", len, user); + if (stURL.fields[HV_URL_PASSWORD].len > 0) { + const char* pswd = strURL + stURL.fields[HV_URL_PASSWORD].off; + int len = stURL.fields[HV_URL_PASSWORD].len; + assert(len == 4); + assert(strncmp(pswd, "pswd", len) == 0); + printf(":%.*s", len, pswd); + } + printf("@"); + } + // host:port + if (stURL.fields[HV_URL_HOST].len > 0) { + const char* host = strURL + stURL.fields[HV_URL_HOST].off; + int len = stURL.fields[HV_URL_HOST].len; + assert(len == strlen("www.example.com")); + assert(strncmp(host, "www.example.com", len) == 0); + printf("%.*s", len, host); + if (stURL.fields[HV_URL_PORT].len > 0) { + const char* port = strURL + stURL.fields[HV_URL_PORT].off; + int len = stURL.fields[HV_URL_PORT].len; + assert(len == 2); + assert(strncmp(port, "80", len) == 0); + printf(":%.*s", len, port); + } + } + // /path + if (stURL.fields[HV_URL_PATH].len > 0) { + const char* path = strURL + stURL.fields[HV_URL_PATH].off; + int len = stURL.fields[HV_URL_PATH].len; + assert(len == 5); + assert(strncmp(path, "/path", len) == 0); + printf("%.*s", len, path); + } + // ?query + if (stURL.fields[HV_URL_QUERY].len > 0) { + const char* query = strURL + stURL.fields[HV_URL_QUERY].off; + int len = stURL.fields[HV_URL_QUERY].len; + assert(len == 5); + assert(strncmp(query, "query", len) == 0); + printf("?%.*s", len, query); + } + // #fragment + if (stURL.fields[HV_URL_FRAGMENT].len > 0) { + const char* fragment = strURL + stURL.fields[HV_URL_FRAGMENT].off; + int len = stURL.fields[HV_URL_FRAGMENT].len; + assert(len == 8); + assert(strncmp(fragment, "fragment", len) == 0); + printf("#%.*s", len, fragment); + } + printf("\n"); + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hmutex_test.c b/external/libhv/libhv-1.3.2/unittest/hmutex_test.c new file mode 100644 index 0000000..b255a13 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hmutex_test.c @@ -0,0 +1,134 @@ +#include "hthread.h" +#include "hmutex.h" +#include "htime.h" + +void once_print() { + printf("exec once\n"); +} + +HTHREAD_ROUTINE(test_once) { + honce_t once = HONCE_INIT; + for (int i = 0; i < 10; ++i) { + honce(&once, once_print); + } + printf("honce test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_mutex) { + hmutex_t mutex; + hmutex_init(&mutex); + hmutex_lock(&mutex); + hmutex_unlock(&mutex); + hmutex_destroy(&mutex); + printf("hmutex test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_recursive_mutex) { + hrecursive_mutex_t mutex; + hrecursive_mutex_init(&mutex); + hrecursive_mutex_lock(&mutex); + hrecursive_mutex_lock(&mutex); + hrecursive_mutex_unlock(&mutex); + hrecursive_mutex_unlock(&mutex); + hrecursive_mutex_destroy(&mutex); + printf("hrecursive_mutex test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_spinlock) { + hspinlock_t spin; + hspinlock_init(&spin); + hspinlock_lock(&spin); + hspinlock_unlock(&spin); + hspinlock_destroy(&spin); + printf("hspinlock test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_rwlock) { + hrwlock_t rwlock; + hrwlock_init(&rwlock); + hrwlock_rdlock(&rwlock); + hrwlock_rdunlock(&rwlock); + hrwlock_wrlock(&rwlock); + hrwlock_wrunlock(&rwlock); + hrwlock_destroy(&rwlock); + printf("hrwlock test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_timed_mutex) { + htimed_mutex_t mutex; + htimed_mutex_init(&mutex); + htimed_mutex_lock(&mutex); + time_t start_time = gettick_ms(); + htimed_mutex_lock_for(&mutex, 3000); + time_t end_time = gettick_ms(); + printf("htimed_mutex_lock_for %zdms\n", end_time - start_time); + htimed_mutex_unlock(&mutex); + htimed_mutex_destroy(&mutex); + printf("htimed_mutex test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_condvar) { + hmutex_t mutex; + hmutex_init(&mutex); + hcondvar_t cv; + hcondvar_init(&cv); + + hmutex_lock(&mutex); + hcondvar_signal(&cv); + hcondvar_broadcast(&cv); + time_t start_time = gettick_ms(); + hcondvar_wait_for(&cv, &mutex, 3000); + time_t end_time = gettick_ms(); + printf("hcondvar_wait_for %zdms\n", end_time - start_time); + hmutex_unlock(&mutex); + + hmutex_destroy(&mutex); + hcondvar_destroy(&cv); + printf("hcondvar test OK!\n"); + return 0; +} + +HTHREAD_ROUTINE(test_sem) { + hsem_t sem; + hsem_init(&sem, 10); + for (int i = 0; i < 10; ++i) { + hsem_wait(&sem); + } + hsem_post(&sem); + hsem_wait(&sem); + time_t start_time = gettick_ms(); + hsem_wait_for(&sem, 3000); + time_t end_time = gettick_ms(); + printf("hsem_wait_for %zdms\n", end_time - start_time); + hsem_destroy(&sem); + printf("hsem test OK!\n"); + return 0; +} + +int main(int argc, char* argv[]) { + hthread_t thread_once = hthread_create(test_once, NULL); + hthread_t thread_mutex = hthread_create(test_mutex, NULL); + hthread_t thread_recursive_mutex = hthread_create(test_recursive_mutex, NULL); + hthread_t thread_spinlock = hthread_create(test_spinlock, NULL); + hthread_t thread_rwlock = hthread_create(test_rwlock, NULL); + hthread_t thread_timed_mutex = hthread_create(test_timed_mutex, NULL); + hthread_t thread_condvar = hthread_create(test_condvar, NULL); + hthread_t thread_sem = hthread_create(test_sem, NULL); + + hthread_join(thread_once); + hthread_join(thread_mutex); + hthread_join(thread_recursive_mutex); + hthread_join(thread_spinlock); + hthread_join(thread_rwlock); + hthread_join(thread_timed_mutex); + hthread_join(thread_condvar); + hthread_join(thread_sem); + printf("hthread test OK!\n"); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hpath_test.cpp b/external/libhv/libhv-1.3.2/unittest/hpath_test.cpp new file mode 100644 index 0000000..4003c22 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hpath_test.cpp @@ -0,0 +1,15 @@ +#include "hpath.h" + +int main(int argc, char** argv) { + std::string filepath = HPath::join("/mnt/share/image", "test.jpg"); + std::string basename = HPath::basename(filepath); + std::string dirname = HPath::dirname(filepath); + std::string filename = HPath::filename(filepath); + std::string suffixname = HPath::suffixname(filepath); + printf("filepath = %s\n", filepath.c_str()); + printf("basename = %s\n", basename.c_str()); + printf("dirname = %s\n", dirname.c_str()); + printf("filename = %s\n", filename.c_str()); + printf("suffixname = %s\n", suffixname.c_str()); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hstring_test.cpp b/external/libhv/libhv-1.3.2/unittest/hstring_test.cpp new file mode 100644 index 0000000..41173f1 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hstring_test.cpp @@ -0,0 +1,43 @@ +#include "hstring.h" +using namespace hv; + +int main(int argc, char** argv) { + std::string str1 = "a1B2*C3d4=="; + std::string str2 = "a1B2*C3d4=="; + println("toupper=" + toupper(str1)); + println("tolower=" + tolower(str2)); + std::string str3 = "abcdefg"; + println("reverse=" + reverse(str3)); + + std::string str4 = "123456789"; + printf("startswith=%d\nendswith=%d\ncontains=%d\n", + (int)startswith(str4, "123"), + (int)endswith(str4, "789"), + (int)contains(str4, "456")); + + std::string str5 = asprintf("%s%d", "hello", 5); + println("asprintf=" + str5); + + std::string str6("123,456,789"); + StringList strlist = split(str6, ','); + println("split " + str6); + for (auto& str : strlist) { + println(str); + } + + std::string str7("user=admin&pswd=123456"); + hv::KeyValue kv = splitKV(str7, '&', '='); + for (auto& pair : kv) { + printf("%s=%s\n", pair.first.c_str(), pair.second.c_str()); + } + + std::string str8(""); + std::string str9 = trim_pairs(str8); + println("trim_pairs=" + str9); + + std::string str10("{{title}}"); + std::string str11 = replace(str10, "{{title}}", "Home"); + println("replace=" + str11); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hthread_test.cpp b/external/libhv/libhv-1.3.2/unittest/hthread_test.cpp new file mode 100644 index 0000000..b284129 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hthread_test.cpp @@ -0,0 +1,59 @@ +#include "hthread.h" +#include "htime.h" + +HTHREAD_ROUTINE(test_thread1) { + int cnt = 10; + while (cnt-- > 0) { + printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); + hv_msleep(100); + } + return 0; +} + +class TestThread2 : public HThread { +protected: + virtual void run() { + int cnt = 10; + while (cnt-- > 0) { + printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); + hv_msleep(100); + } + } +}; + +class TestThread3 : public HThread { +protected: + virtual bool doPrepare() { + printf("doPrepare\n"); + return true; + } + + virtual void doTask() { + printf("tid=%ld time=%llums\n", hv_gettid(), gettimeofday_ms()); + } + + virtual bool doFinish() { + printf("doFinish\n"); + return true; + } +}; + +int main() { + printf("c-style hthread_create\n"); + hthread_t thread1 = hthread_create(test_thread1, NULL); + hthread_join(thread1); + + printf("cpp-style override HThread::run\n"); + TestThread2 thread2; + thread2.start(); + thread2.stop(); + + printf("cpp-style override HThread::doTask\n"); + TestThread3 thread3; + thread3.setSleepPolicy(HThread::SLEEP_UNTIL, 100); + thread3.start(); + hv_sleep(1); + thread3.stop(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/hurl_test.cpp b/external/libhv/libhv-1.3.2/unittest/hurl_test.cpp new file mode 100644 index 0000000..7319746 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/hurl_test.cpp @@ -0,0 +1,23 @@ +#include + +#include "hurl.h" + +int main(int argc, char** argv) { + std::string strURL = "http://www.example.com/path?query#fragment"; + HUrl url; + if (!url.parse(strURL)) { + printf("parse url %s error!\n", strURL.c_str()); + return -1; + } + std::string dumpURL = url.dump(); + printf("%s =>\n%s\n", strURL.c_str(), dumpURL.c_str()); + assert(strURL == dumpURL); + + const char* str = "中 文"; + std::string escaped = HUrl::escape(str); + std::string unescaped = HUrl::unescape(escaped.c_str()); + printf("%s => %s\n", str, escaped.c_str()); + assert(str == unescaped); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/ifconfig_test.cpp b/external/libhv/libhv-1.3.2/unittest/ifconfig_test.cpp new file mode 100644 index 0000000..b85b783 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/ifconfig_test.cpp @@ -0,0 +1,17 @@ +#include + +#include "ifconfig.h" + +int main() { + std::vector ifcs; + ifconfig(ifcs); + for (auto& item : ifcs) { + printf("%s\nip: %s\nmask: %s\nbroadcast: %s\nmac: %s\n\n", + item.name, + item.ip, + item.mask, + item.broadcast, + item.mac); + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/listdir_test.cpp b/external/libhv/libhv-1.3.2/unittest/listdir_test.cpp new file mode 100644 index 0000000..d49486d --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/listdir_test.cpp @@ -0,0 +1,44 @@ +#include + +#include "hdir.h" + +int main(int argc, char* argv[]) { + const char* dir = "."; + if (argc > 1) { + dir = argv[1]; + } + std::list dirs; + listdir(dir, dirs); + for (auto& item : dirs) { + printf("%c%c%c%c%c%c%c%c%c%c\t", + item.type, + (item.mode & 0400) ? 'r' : '-', + (item.mode & 0200) ? 'w' : '-', + (item.mode & 0100) ? 'x' : '-', + (item.mode & 0040) ? 'r' : '-', + (item.mode & 0020) ? 'w' : '-', + (item.mode & 0010) ? 'x' : '-', + (item.mode & 0004) ? 'r' : '-', + (item.mode & 0002) ? 'w' : '-', + (item.mode & 0001) ? 'x' : '-'); + float hsize; + if (item.size < 1024) { + printf("%lu\t", item.size); + } + else if ((hsize = item.size/1024.0f) < 1024.0f) { + printf("%.1fK\t", hsize); + } + else if ((hsize /= 1024.0f) < 1024.0f) { + printf("%.1fM\t", hsize); + } + else { + hsize /= 1024.0f; + printf("%.1fG\t", hsize); + } + struct tm* tm = localtime(&item.mtime); + printf("%04d-%02d-%02d %02d:%02d:%02d\t", + tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); + printf("%s%s\n", item.name, item.type == 'd' ? "/" : ""); + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/md5_test.c b/external/libhv/libhv-1.3.2/unittest/md5_test.c new file mode 100644 index 0000000..41fb4d4 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/md5_test.c @@ -0,0 +1,64 @@ +/* + * @build: gcc -o bin/md5 unittest/md5_test.c util/md5.c -I. -Iutil + * + */ + +#include +#include +#include +#include + +#include "md5.h" + +static void test() { + unsigned char ch = '1'; + char md5[33] = {0}; + hv_md5_hex(&ch, 1, md5, sizeof(md5)); + assert(strcmp(md5, "c4ca4238a0b923820dcc509a6f75849b") == 0); +} + +int main(int argc, char* argv[]) { + test(); + + if (argc < 2) { + printf("Usage: md5 file\n"); + printf(" md5 -s string\n"); + return -10; + } + + char md5[33] = {0}; + + if (argc == 2) { + const char* filepath = argv[1]; + FILE* fp = fopen(filepath, "rb"); + if (fp == NULL) { + printf("Open file '%s' failed!\n", filepath); + return -20; + } + fseek(fp, 0, SEEK_END); + long filesize = ftell(fp); + // printf("filesize=%ld\n", filesize); + fseek(fp, 0, SEEK_SET); + unsigned char* filebuf = (unsigned char*)malloc(filesize); + size_t nread = fread(filebuf, 1, filesize, fp); + assert(nread == filesize); + hv_md5_hex(filebuf, filesize, md5, sizeof(md5)); + + free(filebuf); + fclose(fp); + } + else if (argc == 3) { + const char* flags = argv[1]; + if (flags[0] == '-' && flags[1] == 's') { + hv_md5_hex((unsigned char*)argv[2], strlen(argv[2]), md5, sizeof(md5)); + } + else { + printf("Unrecognized flags '%s'\n", flags); + return -40; + } + } + + puts(md5); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/mkdir_test.c b/external/libhv/libhv-1.3.2/unittest/mkdir_test.c new file mode 100644 index 0000000..8f11444 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/mkdir_test.c @@ -0,0 +1,10 @@ +#include "hbase.h" + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: mkdir_p dir\n"); + return -1; + } + const char* dir = argv[1]; + return hv_mkdir_p(dir); +} diff --git a/external/libhv/libhv-1.3.2/unittest/nslookup_test.c b/external/libhv/libhv-1.3.2/unittest/nslookup_test.c new file mode 100644 index 0000000..eaa972b --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/nslookup_test.c @@ -0,0 +1,34 @@ +#include + +#include "hplatform.h" // inet_ntop +#include "dns.h" // nslookup + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: nslookup domain [nameserver]\n"); + return -1; + } + + const char* domain = argv[1]; + const char* nameserver = "127.0.1.1"; +#ifndef OS_LINUX + nameserver = "114.114.114.114"; + // nameserver = "8.8.8.8"; +#endif + + if (argc > 2) { + nameserver = argv[2]; + } + + uint32_t addrs[16]; + int naddr = nslookup(domain, addrs, 16, nameserver); + if (naddr < 0) { + return naddr; + } + char ip[16]; + for (int i = 0; i < naddr; ++i) { + inet_ntop(AF_INET, (void*)&addrs[i], ip, 16); + printf("%s\n", ip); + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/objectpool_test.cpp b/external/libhv/libhv-1.3.2/unittest/objectpool_test.cpp new file mode 100644 index 0000000..6b1cc22 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/objectpool_test.cpp @@ -0,0 +1,56 @@ +#include +#include + +#include "hobjectpool.h" + +#ifdef _WIN32 +#include +#else +#include +#endif + +void msleep(unsigned int ms) { +#ifdef _WIN32 + Sleep(ms); +#else + usleep(ms*1000); +#endif +} + +class Task { +public: + Task() {printf("Task()\n");} + ~Task() {printf("~Task()\n");} + + void Do() { + printf("%p start do...\n", this); + msleep(4000); + printf("%p end do\n", this); + } +}; + +HObjectPool task_pool(1, 5); + +void task_thread(int id) { + printf("thread %d run...\n", id); + HPoolObject pTask(task_pool); + if (pTask) { + pTask->Do(); + } + else { + printf("No available task in pool\n"); + } + printf("thread %d exit\n", id); +} + +int main(int argc, char** argv) { + for (int i = 0; i < 10; ++i) { + new std::thread(task_thread, i); + } + msleep(5000); + for (int i = 10; i < 20; ++i) { + new std::thread(task_thread, i); + } + msleep(10000); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/ping_test.c b/external/libhv/libhv-1.3.2/unittest/ping_test.c new file mode 100644 index 0000000..af4b039 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/ping_test.c @@ -0,0 +1,16 @@ +#include +#include "icmp.h" +#include "hplatform.h" + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: ping host|ip\n"); + return -10; + } + + char* host = argv[1]; + int ping_cnt = 4; + int ok_cnt = ping(host, ping_cnt); + printf("ping %d count, %d ok.\n", ping_cnt, ok_cnt); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/rbtree_test.c b/external/libhv/libhv-1.3.2/unittest/rbtree_test.c new file mode 100644 index 0000000..2e6c61e --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/rbtree_test.c @@ -0,0 +1,111 @@ +#include +#include + +#include "rbtree.h" + +typedef int rbtree_key_type; +typedef int rbtree_val_type; + +struct rbtree_entry { + struct rb_node rb_node; + rbtree_key_type key; + rbtree_val_type val; +}; + +int rbtree_insert(struct rb_root* root, struct rbtree_entry* entry) { + printf("insert %d\n", entry->key); + struct rb_node** n = &root->rb_node; + struct rb_node* parent = NULL; + struct rbtree_entry* e = NULL; + while (*n) { + parent = *n; + e = rb_entry(*n, struct rbtree_entry, rb_node); + if (entry->key < e->key) { + n = &(*n)->rb_left; + } else if (entry->key > e->key) { + n = &(*n)->rb_right; + } else { + return -1; + } + } + + rb_link_node(&entry->rb_node, parent, n); + rb_insert_color(&entry->rb_node, root); + return 0; +} + +int rbtree_remove(struct rb_root* root, struct rbtree_entry* entry) { + printf("remove %d\n", entry->key); + rb_erase(&entry->rb_node, root); + return 0; +} + +struct rbtree_entry* rbtree_search(struct rb_root* root, const rbtree_key_type* key) { + struct rb_node* n = root->rb_node; + struct rbtree_entry* e = NULL; + while (n) { + e = rb_entry(n, struct rbtree_entry, rb_node); + if (*key < e->key) { + n = n->rb_left; + } else if (*key > e->key) { + n = n->rb_right; + } else { + return e; + } + } + return NULL; +} + +void rbtree_entry_print(struct rbtree_entry* entry) { + if (entry == NULL) { + printf("null\n"); + return; + } + printf("%d:%d\n", entry->key, entry->val); +} + +int main() { + struct rb_root root = { NULL }; + struct rbtree_entry* entry = NULL; + + struct rbtree_entry entries[10]; + for (int i = 0; i < 10; ++i) { + memset(&entries[i], 0, sizeof(struct rbtree_entry)); + entries[i].key = i; + entries[i].val = i; + } + + rbtree_insert(&root, &entries[1]); + rbtree_insert(&root, &entries[2]); + rbtree_insert(&root, &entries[3]); + rbtree_insert(&root, &entries[7]); + rbtree_insert(&root, &entries[8]); + rbtree_insert(&root, &entries[9]); + rbtree_insert(&root, &entries[4]); + rbtree_insert(&root, &entries[5]); + rbtree_insert(&root, &entries[6]); + + rbtree_remove(&root, &entries[1]); + rbtree_remove(&root, &entries[9]); + rbtree_remove(&root, &entries[4]); + rbtree_remove(&root, &entries[6]); + + int key = 5; + entry = rbtree_search(&root, &key); + rbtree_entry_print(entry); + + key = 4; + entry = rbtree_search(&root, &key); + rbtree_entry_print(entry); + + struct rb_node* node = NULL; + // while((node = rb_first(&root))) { + while((node = root.rb_node)) { + entry = rb_entry(node, struct rbtree_entry, rb_node); + rb_erase(node, &root); + rbtree_entry_print(entry); + memset(entry, 0, sizeof(struct rbtree_entry)); + } + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/rmdir_test.c b/external/libhv/libhv-1.3.2/unittest/rmdir_test.c new file mode 100644 index 0000000..a0c5bcb --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/rmdir_test.c @@ -0,0 +1,10 @@ +#include "hbase.h" + +int main(int argc, char* argv[]) { + if (argc < 2) { + printf("Usage: rmdir_p dir\n"); + return -1; + } + const char* dir = argv[1]; + return hv_rmdir_p(dir); +} diff --git a/external/libhv/libhv-1.3.2/unittest/sendmail_test.c b/external/libhv/libhv-1.3.2/unittest/sendmail_test.c new file mode 100644 index 0000000..3e5d09a --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/sendmail_test.c @@ -0,0 +1,24 @@ +#include + +#include "smtp.h" + +int main(int argc, char** argv) { + if (argc < 8) { + printf("Usage: sendmail smtp_server username password from to subject body\n"); + return -10; + } + + const char* smtp_server = argv[1]; + const char* username = argv[2]; + const char* password = argv[3]; + mail_t mail; + mail.from = argv[4]; + mail.to = argv[5]; + mail.subject = argv[6]; + mail.body = argv[7]; + + int status_code = sendmail(smtp_server, username, password, &mail); + printf("sendmail: %d %s\n", status_code, smtp_status_str((enum smtp_status)status_code)); + + return status_code == SMTP_STATUS_OK ? 0 : status_code; +} diff --git a/external/libhv/libhv-1.3.2/unittest/sha1_test.c b/external/libhv/libhv-1.3.2/unittest/sha1_test.c new file mode 100644 index 0000000..326b4cd --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/sha1_test.c @@ -0,0 +1,64 @@ +/* + * @build: gcc -o bin/sha1 unittest/sha1_test.c util/sha1.c -I. -Iutil + * + */ + +#include +#include +#include +#include + +#include "sha1.h" + +static void test() { + unsigned char ch = '1'; + char sha1[41] = {0}; + hv_sha1_hex(&ch, 1, sha1, sizeof(sha1)); + assert(strcmp(sha1, "356a192b7913b04c54574d18c28d46e6395428ab") == 0); +} + +int main(int argc, char* argv[]) { + test(); + + if (argc < 2) { + printf("Usage: sha1 file\n"); + printf(" sha1 -s string\n"); + return -10; + } + + char sha1[41] = {0}; + + if (argc == 2) { + const char* filepath = argv[1]; + FILE* fp = fopen(filepath, "rb"); + if (fp == NULL) { + printf("Open file '%s' failed!\n", filepath); + return -20; + } + fseek(fp, 0, SEEK_END); + long filesize = ftell(fp); + // printf("filesize=%ld\n", filesize); + fseek(fp, 0, SEEK_SET); + unsigned char* filebuf = (unsigned char*)malloc(filesize); + size_t nread = fread(filebuf, 1, filesize, fp); + assert(nread == filesize); + hv_sha1_hex(filebuf, filesize, sha1, sizeof(sha1)); + + free(filebuf); + fclose(fp); + } + else if (argc == 3) { + const char* flags = argv[1]; + if (flags[0] == '-' && flags[1] == 's') { + hv_sha1_hex((unsigned char*)argv[2], strlen(argv[2]), sha1, sizeof(sha1)); + } + else { + printf("Unrecognized flags '%s'\n", flags); + return -40; + } + } + + puts(sha1); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/sizeof_test.cpp b/external/libhv/libhv-1.3.2/unittest/sizeof_test.cpp new file mode 100644 index 0000000..e73d233 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/sizeof_test.cpp @@ -0,0 +1,62 @@ +#include + +#include "hloop.h" +#include "hevent.h" + +#include "EventLoop.h" +#include "EventLoopThread.h" +#include "EventLoopThreadPool.h" +#include "Channel.h" +#include "TcpClient.h" +#include "TcpServer.h" +#include "UdpClient.h" +#include "UdpServer.h" + +#include "HttpMessage.h" +#include "Http1Parser.h" +#include "HttpContext.h" +#include "HttpServer.h" +#include "HttpHandler.h" +#include "HttpResponseWriter.h" + +#include "WebSocketChannel.h" +#include "WebSocketParser.h" +#include "WebSocketServer.h" +#include "WebSocketClient.h" + +using namespace hv; + +int main() { + // event + printf("sizeof(struct hloop_s)=%lu\n", sizeof(struct hloop_s)); + printf("sizeof(struct hevent_s)=%lu\n", sizeof(struct hevent_s)); + printf("sizeof(struct hidle_s)=%lu\n", sizeof(struct hidle_s)); + printf("sizeof(struct htimer_s)=%lu\n", sizeof(struct htimer_s)); + printf("sizeof(struct htimeout_s)=%lu\n", sizeof(struct htimeout_s)); + printf("sizeof(struct hperiod_s)=%lu\n", sizeof(struct hperiod_s)); + printf("sizeof(struct hio_s)=%lu\n", sizeof(struct hio_s)); + // evpp + printf("sizeof(class EventLoop)=%lu\n", sizeof(EventLoop)); + printf("sizeof(class EventLoopThread)=%lu\n", sizeof(EventLoopThread)); + printf("sizeof(class EventLoopThreadPool)=%lu\n", sizeof(EventLoopThreadPool)); + printf("sizeof(class Channel)=%lu\n", sizeof(Channel)); + printf("sizeof(class SocketChannel)=%lu\n", sizeof(SocketChannel)); + printf("sizeof(class TcpClient)=%lu\n", sizeof(TcpClient)); + printf("sizeof(class TcpServer)=%lu\n", sizeof(TcpServer)); + printf("sizeof(class UdpClient)=%lu\n", sizeof(UdpClient)); + printf("sizeof(class UdpServer)=%lu\n", sizeof(UdpServer)); + // http + printf("sizeof(class HttpRequest)=%lu\n", sizeof(HttpRequest)); + printf("sizeof(class HttpResponse)=%lu\n", sizeof(HttpResponse)); + printf("sizeof(class Http1Parser)=%lu\n", sizeof(Http1Parser)); + printf("sizeof(class HttpContext)=%lu\n", sizeof(HttpContext)); + printf("sizeof(class HttpServer)=%lu\n", sizeof(HttpServer)); + printf("sizeof(class HttpHandler)=%lu\n", sizeof(HttpHandler)); + printf("sizeof(class HttpResponseWrite)=%lu\n", sizeof(HttpResponseWriter)); + // websocket + printf("sizeof(class WebSocketChannel)=%lu\n", sizeof(WebSocketChannel)); + printf("sizeof(class WebSocketParser)=%lu\n", sizeof(WebSocketParser)); + printf("sizeof(class WebSocketClient)=%lu\n", sizeof(WebSocketClient)); + printf("sizeof(class WebSocketServer)=%lu\n", sizeof(WebSocketServer)); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/socketpair_test.c b/external/libhv/libhv-1.3.2/unittest/socketpair_test.c new file mode 100644 index 0000000..b29398e --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/socketpair_test.c @@ -0,0 +1,24 @@ +#include + +#include "hsocket.h" + +int main(int argc, char* argv[]) { + int sockfds[2]; + if (Socketpair(AF_INET, SOCK_STREAM, 0, sockfds) != 0) { + printf("socketpair failed!\n"); + return -1; + } + printf("Socketpair %d<=>%d\n", sockfds[0], sockfds[1]); + + char sendbuf[] = "hello,world!"; + char recvbuf[1460]; + int nsend = send(sockfds[0], sendbuf, strlen(sendbuf), 0); + printf("sockfd:%d send %d bytes: %s\n", sockfds[0], nsend, sendbuf); + memset(recvbuf, 0, sizeof(recvbuf)); + int nrecv = recv(sockfds[1], recvbuf, sizeof(recvbuf), 0); + printf("sockfd:%d recv %d bytes: %s\n", sockfds[1], nrecv, recvbuf); + + closesocket(sockfds[0]); + closesocket(sockfds[1]); + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/synchronized_test.cpp b/external/libhv/libhv-1.3.2/unittest/synchronized_test.cpp new file mode 100644 index 0000000..acfe005 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/synchronized_test.cpp @@ -0,0 +1,24 @@ +#include "hthread.h" +#include "hmutex.h" + +#define THREAD_NUM 10 +std::mutex g_mutex; + +HTHREAD_ROUTINE(test_synchronized) { + synchronized(g_mutex) { + hv_delay(1000); + printf("tid=%ld time=%llus\n", hv_gettid(), (unsigned long long)time(NULL)); + } + return 0; +} + +int main() { + hthread_t threads[THREAD_NUM]; + for (int i = 0; i < THREAD_NUM; ++i) { + threads[i] = hthread_create(test_synchronized, NULL); + } + for (int i = 0; i < THREAD_NUM; ++i) { + hthread_join(threads[i]); + } + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/threadpool_test.cpp b/external/libhv/libhv-1.3.2/unittest/threadpool_test.cpp new file mode 100644 index 0000000..7f9c830 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/threadpool_test.cpp @@ -0,0 +1,30 @@ +#include + +#include "hthreadpool.h" +#include "hthread.h" +#include "htime.h" + +void print_task(int i) { + printf("thread[%ld]: task[%d]\n", hv_gettid(), i); + hv_sleep(1); +} + +int main(int argc, char** argv) { + HThreadPool tp(1, 4); + tp.start(); + + int i = 0; + for (; i < 10; ++i) { + tp.commit(print_task, i); + } + + tp.wait(); + + for (; i < 20; ++i) { + tp.commit(print_task, i); + } + + tp.wait(); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/unittest/webbench.c b/external/libhv/libhv-1.3.2/unittest/webbench.c new file mode 100644 index 0000000..7bac7b6 --- /dev/null +++ b/external/libhv/libhv-1.3.2/unittest/webbench.c @@ -0,0 +1,373 @@ +#include +#include +#include +#include +#include // for gethostbyname + +#include +#include +#include +#include + +#include + +#include +#include + +int Connect(const char* host, int port) { + struct sockaddr_in addr; + addr.sin_family = AF_INET; + in_addr_t inaddr = inet_addr(host); + if (inaddr != INADDR_NONE) { + addr.sin_addr.s_addr = inaddr; + } + else { + struct hostent* phe = gethostbyname(host); + if (phe == NULL) { + return -1; + } + memcpy(&addr.sin_addr, phe->h_addr_list[0], phe->h_length); + } + addr.sin_port = htons(port); + int sock = socket(AF_INET, SOCK_STREAM, 0); + if (sock < 0) { + perror("socket"); + return -2; + } + if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { + perror("connect"); + return -3; + } + return sock; +} + +#define METHOD_GET 0 +#define METHOD_HEAD 1 +#define METHOD_OPTIONS 2 +#define METHOD_TRACE 3 + +#define VERSION "webbench/1.19.3.15" + +int verbose = 0; +int quiet = 0; +volatile int timerexpired = 0; // for timer +int time = 30; +int clients = 1; +char host[64] = {0}; +int port = 80; +char* proxy_host = NULL; +int proxy_port = 80; +int method = METHOD_GET; +int http = 1; // 1=HTTP/1.1 0=HTTP/1.0 +int keepalive = 0; +const char* url = NULL; + +#define REQUEST_SIZE 2048 +char request[REQUEST_SIZE] = {0}; +char buf[1460] = {0}; + +int mypipe[2]; // IPC + +static const char options[] = "?hVvq01kt:p:c:"; + +static const struct option long_options[] = { + {"help", no_argument, NULL, 'h'}, + {"version", no_argument, NULL, 'V'}, + {"verbose", no_argument, NULL, 'v'}, + {"quiet", no_argument, NULL, 'q'}, + {"time", required_argument, NULL, 't'}, + {"proxy", required_argument, NULL, 'p'}, + {"clients", required_argument, NULL, 'c'}, + {"http10", no_argument, NULL, '0'}, + {"http11", no_argument, NULL, '1'}, + {"keepalive", no_argument, NULL, 'k'}, + {"get", no_argument, &method, METHOD_GET}, + {"head", no_argument, &method, METHOD_HEAD}, + {"options", no_argument, &method, METHOD_OPTIONS}, + {"trace", no_argument, &method, METHOD_TRACE}, + {NULL, 0, NULL, 0} +}; + +void print_usage() { + printf("Usage: webbench [%s] URL\n", options); + puts("\n\ +Options:\n\ + -?|-h|--help Print this information.\n\ + -V|--version Print version.\n\ + -v|--verbose Print verbose.\n\ + -q|--quiet Print quiet.\n\ + -0|--http10 Use HTTP/1.0 protocol.\n\ + -1|--http11 Use HTTP/1.1 protocol.\n\ + -k|--keepalive Connection: keep-alive.\n\ + -t|--time Run benchmark for seconds. Default 30.\n\ + -p|--proxy Use proxy server for request.\n\ + -c|--clients Run HTTP clients. Default one.\n\ + --get Use GET request method.\n\ + --head Use HEAD request method.\n\ + --options Use OPTIONS request method.\n\ + --trace Use TRACE request method.\n\ + "); +} + +int parse_cmdline(int argc, char** argv) { + int opt = 0; + int opt_idx = 0; + while ((opt=getopt_long(argc, argv, options, long_options, &opt_idx)) != EOF) { + switch (opt) { + case '?': + case 'h': print_usage(); exit(1); + case 'V': puts(VERSION); exit(1); + case 'v': verbose = 1; break; + case 'q': quiet = 1; break; + case '0': http = 0; break; + case '1': http = 1; break; + case 'k': keepalive = 1; break; + case 't': time = atoi(optarg); break; + case 'c': clients = atoi(optarg); break; + case 'p': + { + // host:port + char* pos = strrchr(optarg, ':'); + proxy_host = optarg; + if (pos == NULL) break; + if (pos == optarg || + pos == optarg + strlen(optarg) - 1) { + printf("Error option --proxy\n"); + return -2; + } + *pos = '\0'; + proxy_port = atoi(pos+1); + } + break; + } + } + + if (optind == argc) { + printf("Missing URL\n"); + return -2; + } + + url = argv[optind]; + + return 0; +} + +static void alarm_handler(int singal) { + timerexpired = 1; +} + +int main(int argc, char** argv) { + if (argc == 1) { + print_usage(); + return 2; + } + + int ret = parse_cmdline(argc, argv); + if (ret != 0) { + return ret; + } + + printf("%d clients, running %d sec\n", clients, time); + + // domain port url + const char* req_url = "/"; + if (proxy_host) { + strncpy(host, proxy_host, sizeof(host)); + port = proxy_port; + } else { + // http://host:port/path + const char* pos1 = strstr(url, "http://"); + if (pos1 == NULL) { + pos1 = url; + } else { + pos1 += strlen("http://"); + } + const char* pos2 = strchr(pos1, '/'); + if (pos2 == NULL) { + pos2 = url + strlen(url); + } else { + req_url = pos2; + } + int len = pos2 - pos1; + char* server = (char*)malloc(len+1); + memcpy(server, pos1, len); + server[len] = '\0'; + char* pos3 = strrchr(server, ':'); + if (pos3 == NULL) { + port = 80; + } else { + *pos3 = '\0'; + port = atoi(pos3+1); + } + strncpy(host, server, sizeof(host)); + free(server); + } + char Host[256]; + snprintf(Host, sizeof(Host), "Host: %s:%d\r\n", host, port); + printf("%s", Host); + + // test connect + int sock = Connect(host, port); + if (sock < 0) { + printf("Connect failed!\n"); + return -20; + } else { + printf("Connect test OK!\n"); + close(sock); + } + + // build request + switch (method) { + case METHOD_GET: + default: + strcpy(request, "GET"); + break; + case METHOD_HEAD: + strcpy(request, "HEAD"); + break; + case METHOD_OPTIONS: + strcpy(request, "OPTIONS"); + break; + case METHOD_TRACE: + strcpy(request, "TRACE"); + break; + } + + strcat(request, " "); + strcat(request, req_url); + strcat(request, " "); + if (http == 0) { + strcat(request, "HTTP/1.0"); + } else if (http == 1) { + strcat(request, "HTTP/1.1"); + } + strcat(request, "\r\n"); + strcat(request, "User-Agent: webbench/1.18.3.15\r\n"); + strcat(request, Host); + strcat(request, "Cache-Control: no-cache\r\n"); + if (keepalive) { + strcat(request, "Connection: keep-alive\r\n"); + } + else { + strcat(request, "Connection: close\r\n"); + } + strcat(request, "\r\n"); + if (!quiet) { + printf("%s", request); + } + + // IPC + if (pipe(mypipe) < 0) { + perror("pipe"); + exit(20); + } + + // fork childs + pid_t pid = 0; + FILE* fp = NULL; + long long succeed = 0, failed = 0, bytes = 0; + int childs = clients; + int i; + for (i = 0; i < childs; ++i) { + pid = fork(); + if (pid < 0) { + perror("fork"); + exit(-10); + } + + if (pid == 0) { + // child + //printf("child[%d] start\n", getpid()); + signal(SIGALRM, alarm_handler); + alarm(time); + int sock = -1; + int len = strlen(request); + int wrbytes, rdbytes; + while (1) { +connect: + if (timerexpired) break; + if (sock == -1) { + sock = Connect(host, port); + } + if (sock < 0) { + ++failed; + continue; + } + int total_rdbytes = 0; +write: + if (timerexpired) break; + wrbytes = write(sock, request, len); + if (verbose) { + printf("write %d bytes\n", wrbytes); + } + if (wrbytes != len) { + ++failed; + goto close; + } + if (verbose) { + printf("%s\n", request); + } +read: + if (timerexpired) break; + rdbytes = read(sock, buf, sizeof(buf)); + if (verbose) { + printf("read %d bytes\n", rdbytes); + } + if (rdbytes <= 0) { + ++failed; + goto close; + } + if (verbose) { + printf("%.*s\n", rdbytes, buf); + } + static int s_rdbytes = 0; + if (s_rdbytes == 0) { + s_rdbytes = rdbytes; + } + bytes += rdbytes; + total_rdbytes += rdbytes; + if (total_rdbytes < s_rdbytes) { + // NOTE: some http server head and body send not one packet. + goto read; + } + ++succeed; +close: + if (!keepalive) { + close(sock); + sock = -1; + } + } + + fp = fdopen(mypipe[1], "w"); + if (fp == NULL) { + perror("fdopen"); + return 30; + } + fprintf(fp, "%lld %lld %lld\n", succeed, failed, bytes); + fclose(fp); + //printf("child[%d] end\n", getpid()); + return 0; + } + } + + fp = fdopen(mypipe[0], "r"); + if (fp == NULL) { + perror("fdopen"); + return 30; + } + while (1) { + long long i,j,k; + fscanf(fp, "%lld %lld %lld", &i, &j, &k); + succeed += i; + failed += j; + bytes += k; + if (--childs==0) break; + } + fclose(fp); + printf("recv %lld bytes/sec, %lld succeed, %lld failed\n", + bytes/time, + succeed, + failed); + + return 0; +} diff --git a/external/libhv/libhv-1.3.2/util/README.md b/external/libhv/libhv-1.3.2/util/README.md new file mode 100644 index 0000000..b5fc90e --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/README.md @@ -0,0 +1,9 @@ +## 目录结构 + +``` +. +├── base64.h BASE64编解码 +├── md5.h MD5数字摘要 +└── sha1.h SHA1安全散列算法 + +``` diff --git a/external/libhv/libhv-1.3.2/util/base64.c b/external/libhv/libhv-1.3.2/util/base64.c new file mode 100644 index 0000000..80e8e55 --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/base64.c @@ -0,0 +1,126 @@ +#include + +#include "base64.h" + +/* BASE 64 encode table */ +static const char base64en[] = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', + 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', + 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', + 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', + 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', + '4', '5', '6', '7', '8', '9', '+', '/', +}; + +#define BASE64_PAD '=' +#define BASE64DE_FIRST '+' +#define BASE64DE_LAST 'z' +/* ASCII order for BASE 64 decode, -1 in unused character */ +static const signed char base64de[] = { + /* '+', ',', '-', '.', '/', '0', '1', '2', */ + 62, -1, -1, -1, 63, 52, 53, 54, + + /* '3', '4', '5', '6', '7', '8', '9', ':', */ + 55, 56, 57, 58, 59, 60, 61, -1, + + /* ';', '<', '=', '>', '?', '@', 'A', 'B', */ + -1, -1, -1, -1, -1, -1, 0, 1, + + /* 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', */ + 2, 3, 4, 5, 6, 7, 8, 9, + + /* 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', */ + 10, 11, 12, 13, 14, 15, 16, 17, + + /* 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', */ + 18, 19, 20, 21, 22, 23, 24, 25, + + /* '[', '\', ']', '^', '_', '`', 'a', 'b', */ + -1, -1, -1, -1, -1, -1, 26, 27, + + /* 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', */ + 28, 29, 30, 31, 32, 33, 34, 35, + + /* 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', */ + 36, 37, 38, 39, 40, 41, 42, 43, + + /* 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', */ + 44, 45, 46, 47, 48, 49, 50, 51, +}; + +int hv_base64_encode(const unsigned char *in, unsigned int inlen, char *out) { + unsigned int i = 0, j = 0; + + for (; i < inlen; i++) { + int s = i % 3; + + switch (s) { + case 0: + out[j++] = base64en[(in[i] >> 2) & 0x3F]; + continue; + case 1: + out[j++] = base64en[((in[i-1] & 0x3) << 4) + ((in[i] >> 4) & 0xF)]; + continue; + case 2: + out[j++] = base64en[((in[i-1] & 0xF) << 2) + ((in[i] >> 6) & 0x3)]; + out[j++] = base64en[in[i] & 0x3F]; + } + } + + /* move back */ + i -= 1; + + /* check the last and add padding */ + if ((i % 3) == 0) { + out[j++] = base64en[(in[i] & 0x3) << 4]; + out[j++] = BASE64_PAD; + out[j++] = BASE64_PAD; + } else if ((i % 3) == 1) { + out[j++] = base64en[(in[i] & 0xF) << 2]; + out[j++] = BASE64_PAD; + } + + return j; +} + +int hv_base64_decode(const char *in, unsigned int inlen, unsigned char *out) { + unsigned int i = 0, j = 0; + + for (; i < inlen; i++) { + int c; + int s = i % 4; + + if (in[i] == '=') + return j; + + if (in[i] < BASE64DE_FIRST || in[i] > BASE64DE_LAST || + (c = base64de[in[i] - BASE64DE_FIRST]) == -1) + return -1; + + switch (s) { + case 0: + out[j] = ((unsigned int)c << 2) & 0xFF; + continue; + case 1: + out[j++] += ((unsigned int)c >> 4) & 0x3; + + /* if not last char with padding */ + if (i < (inlen - 3) || in[inlen - 2] != '=') + out[j] = ((unsigned int)c & 0xF) << 4; + continue; + case 2: + out[j++] += ((unsigned int)c >> 2) & 0xF; + + /* if not last char with padding */ + if (i < (inlen - 2) || in[inlen - 1] != '=') + out[j] = ((unsigned int)c & 0x3) << 6; + continue; + case 3: + out[j++] += (unsigned char)c; + } + } + + return j; +} diff --git a/external/libhv/libhv-1.3.2/util/base64.h b/external/libhv/libhv-1.3.2/util/base64.h new file mode 100644 index 0000000..ed24c0a --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/base64.h @@ -0,0 +1,46 @@ +#ifndef HV_BASE64_H_ +#define HV_BASE64_H_ + +#include "hexport.h" + +#define BASE64_ENCODE_OUT_SIZE(s) (((s) + 2) / 3 * 4) +#define BASE64_DECODE_OUT_SIZE(s) (((s)) / 4 * 3) + +BEGIN_EXTERN_C + +// @return encoded size +HV_EXPORT int hv_base64_encode(const unsigned char *in, unsigned int inlen, char *out); + +// @return decoded size +HV_EXPORT int hv_base64_decode(const char *in, unsigned int inlen, unsigned char *out); + +END_EXTERN_C + +#ifdef __cplusplus + +#include +#include + +namespace hv { + +HV_INLINE std::string Base64Encode(const unsigned char* data, unsigned int len) { + int encoded_size = BASE64_ENCODE_OUT_SIZE(len); + std::string encoded_str(encoded_size + 1, 0); + encoded_size = hv_base64_encode(data, len, (char*)encoded_str.data()); + encoded_str.resize(encoded_size); + return encoded_str; +} + +HV_INLINE std::string Base64Decode(const char* str, unsigned int len = 0) { + if (len == 0) len = strlen(str); + int decoded_size = BASE64_DECODE_OUT_SIZE(len); + std::string decoded_buf(decoded_size + 1, 0); + decoded_size = hv_base64_decode(str, len, (unsigned char*)decoded_buf.data()); + decoded_buf.resize(decoded_size); + return decoded_buf; +} + +} +#endif + +#endif // HV_BASE64_H_ diff --git a/external/libhv/libhv-1.3.2/util/md5.c b/external/libhv/libhv-1.3.2/util/md5.c new file mode 100644 index 0000000..21f6c9f --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/md5.c @@ -0,0 +1,215 @@ +#include + +#include "md5.h" + +#define F(x,y,z) ((x & y) | (~x & z)) +#define G(x,y,z) ((x & z) | (y & ~z)) +#define H(x,y,z) (x^y^z) +#define I(x,y,z) (y ^ (x | ~z)) +#define ROTATE_LEFT(x,n) ((x << n) | (x >> (32-n))) +#define FF(a,b,c,d,x,s,ac) \ + { \ + a += F(b,c,d) + x + ac; \ + a = ROTATE_LEFT(a,s); \ + a += b; \ + } +#define GG(a,b,c,d,x,s,ac) \ + { \ + a += G(b,c,d) + x + ac; \ + a = ROTATE_LEFT(a,s); \ + a += b; \ + } +#define HH(a,b,c,d,x,s,ac) \ + { \ + a += H(b,c,d) + x + ac; \ + a = ROTATE_LEFT(a,s); \ + a += b; \ + } +#define II(a,b,c,d,x,s,ac) \ + { \ + a += I(b,c,d) + x + ac; \ + a = ROTATE_LEFT(a,s); \ + a += b; \ + } + +static void HV_MD5Transform(unsigned int state[4],unsigned char block[64]); +static void HV_MD5Encode(unsigned char *output,unsigned int *input,unsigned int len); +static void HV_MD5Decode(unsigned int *output,unsigned char *input,unsigned int len); + +static unsigned char PADDING[] = { + 0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 +}; + +void HV_MD5Init(HV_MD5_CTX *ctx) { + ctx->count[0] = 0; + ctx->count[1] = 0; + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; +} + +void HV_MD5Update(HV_MD5_CTX *ctx,unsigned char *input,unsigned int inputlen) { + unsigned int i = 0,index = 0,partlen = 0; + index = (ctx->count[0] >> 3) & 0x3F; + partlen = 64 - index; + ctx->count[0] += inputlen << 3; + if(ctx->count[0] < (inputlen << 3)) { + ctx->count[1]++; + } + ctx->count[1] += inputlen >> 29; + + if(inputlen >= partlen) { + memcpy(&ctx->buffer[index],input,partlen); + HV_MD5Transform(ctx->state,ctx->buffer); + for(i = partlen;i+64 <= inputlen;i+=64) { + HV_MD5Transform(ctx->state,&input[i]); + } + index = 0; + } else { + i = 0; + } + + memcpy(&ctx->buffer[index],&input[i],inputlen-i); +} + +void HV_MD5Final(HV_MD5_CTX *ctx,unsigned char digest[16]) { + unsigned int index = 0,padlen = 0; + unsigned char bits[8]; + index = (ctx->count[0] >> 3) & 0x3F; + padlen = (index < 56)?(56-index):(120-index); + HV_MD5Encode(bits,ctx->count,8); + HV_MD5Update(ctx,PADDING,padlen); + HV_MD5Update(ctx,bits,8); + HV_MD5Encode(digest,ctx->state,16); +} + +void HV_MD5Encode(unsigned char *output,unsigned int *input,unsigned int len) { + unsigned int i = 0,j = 0; + while(j < len) { + output[j] = input[i] & 0xFF; + output[j+1] = (input[i] >> 8) & 0xFF; + output[j+2] = (input[i] >> 16) & 0xFF; + output[j+3] = (input[i] >> 24) & 0xFF; + i++; + j+=4; + } +} + +void HV_MD5Decode(unsigned int *output,unsigned char *input,unsigned int len) { + unsigned int i = 0,j = 0; + while(j < len) { + output[i] = (input[j]) | (input[j+1] << 8) | (input[j+2] << 16) | (input[j+3] << 24); + i++; + j+=4; + } +} + +void HV_MD5Transform(unsigned int state[4],unsigned char block[64]) { + unsigned int a = state[0]; + unsigned int b = state[1]; + unsigned int c = state[2]; + unsigned int d = state[3]; + unsigned int x[64]; + + HV_MD5Decode(x,block,64); + + FF(a, b, c, d, x[ 0], 7, 0xd76aa478); + FF(d, a, b, c, x[ 1], 12, 0xe8c7b756); + FF(c, d, a, b, x[ 2], 17, 0x242070db); + FF(b, c, d, a, x[ 3], 22, 0xc1bdceee); + FF(a, b, c, d, x[ 4], 7, 0xf57c0faf); + FF(d, a, b, c, x[ 5], 12, 0x4787c62a); + FF(c, d, a, b, x[ 6], 17, 0xa8304613); + FF(b, c, d, a, x[ 7], 22, 0xfd469501); + FF(a, b, c, d, x[ 8], 7, 0x698098d8); + FF(d, a, b, c, x[ 9], 12, 0x8b44f7af); + FF(c, d, a, b, x[10], 17, 0xffff5bb1); + FF(b, c, d, a, x[11], 22, 0x895cd7be); + FF(a, b, c, d, x[12], 7, 0x6b901122); + FF(d, a, b, c, x[13], 12, 0xfd987193); + FF(c, d, a, b, x[14], 17, 0xa679438e); + FF(b, c, d, a, x[15], 22, 0x49b40821); + + GG(a, b, c, d, x[ 1], 5, 0xf61e2562); + GG(d, a, b, c, x[ 6], 9, 0xc040b340); + GG(c, d, a, b, x[11], 14, 0x265e5a51); + GG(b, c, d, a, x[ 0], 20, 0xe9b6c7aa); + GG(a, b, c, d, x[ 5], 5, 0xd62f105d); + GG(d, a, b, c, x[10], 9, 0x2441453); + GG(c, d, a, b, x[15], 14, 0xd8a1e681); + GG(b, c, d, a, x[ 4], 20, 0xe7d3fbc8); + GG(a, b, c, d, x[ 9], 5, 0x21e1cde6); + GG(d, a, b, c, x[14], 9, 0xc33707d6); + GG(c, d, a, b, x[ 3], 14, 0xf4d50d87); + GG(b, c, d, a, x[ 8], 20, 0x455a14ed); + GG(a, b, c, d, x[13], 5, 0xa9e3e905); + GG(d, a, b, c, x[ 2], 9, 0xfcefa3f8); + GG(c, d, a, b, x[ 7], 14, 0x676f02d9); + GG(b, c, d, a, x[12], 20, 0x8d2a4c8a); + + HH(a, b, c, d, x[ 5], 4, 0xfffa3942); + HH(d, a, b, c, x[ 8], 11, 0x8771f681); + HH(c, d, a, b, x[11], 16, 0x6d9d6122); + HH(b, c, d, a, x[14], 23, 0xfde5380c); + HH(a, b, c, d, x[ 1], 4, 0xa4beea44); + HH(d, a, b, c, x[ 4], 11, 0x4bdecfa9); + HH(c, d, a, b, x[ 7], 16, 0xf6bb4b60); + HH(b, c, d, a, x[10], 23, 0xbebfbc70); + HH(a, b, c, d, x[13], 4, 0x289b7ec6); + HH(d, a, b, c, x[ 0], 11, 0xeaa127fa); + HH(c, d, a, b, x[ 3], 16, 0xd4ef3085); + HH(b, c, d, a, x[ 6], 23, 0x4881d05); + HH(a, b, c, d, x[ 9], 4, 0xd9d4d039); + HH(d, a, b, c, x[12], 11, 0xe6db99e5); + HH(c, d, a, b, x[15], 16, 0x1fa27cf8); + HH(b, c, d, a, x[ 2], 23, 0xc4ac5665); + + II(a, b, c, d, x[ 0], 6, 0xf4292244); + II(d, a, b, c, x[ 7], 10, 0x432aff97); + II(c, d, a, b, x[14], 15, 0xab9423a7); + II(b, c, d, a, x[ 5], 21, 0xfc93a039); + II(a, b, c, d, x[12], 6, 0x655b59c3); + II(d, a, b, c, x[ 3], 10, 0x8f0ccc92); + II(c, d, a, b, x[10], 15, 0xffeff47d); + II(b, c, d, a, x[ 1], 21, 0x85845dd1); + II(a, b, c, d, x[ 8], 6, 0x6fa87e4f); + II(d, a, b, c, x[15], 10, 0xfe2ce6e0); + II(c, d, a, b, x[ 6], 15, 0xa3014314); + II(b, c, d, a, x[13], 21, 0x4e0811a1); + II(a, b, c, d, x[ 4], 6, 0xf7537e82); + II(d, a, b, c, x[11], 10, 0xbd3af235); + II(c, d, a, b, x[ 2], 15, 0x2ad7d2bb); + II(b, c, d, a, x[ 9], 21, 0xeb86d391); + + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; +} + +void hv_md5(unsigned char* input, unsigned int inputlen, unsigned char digest[16]) { + HV_MD5_CTX ctx; + HV_MD5Init(&ctx); + HV_MD5Update(&ctx, input, inputlen); + HV_MD5Final(&ctx, digest); +} + +static inline char i2hex(unsigned char i) { + return i < 10 ? i + '0' : i - 10 + 'a'; +} + +void hv_md5_hex(unsigned char* input, unsigned int inputlen, char* output, unsigned int outputlen) { + int i; + unsigned char digest[16]; + if (outputlen < 32) return; + hv_md5(input, inputlen, digest); + for (i = 0; i < 16; ++i) { + *output++ = i2hex(digest[i] >> 4); + *output++ = i2hex(digest[i] & 0x0F); + } + if (outputlen > 32) *output = '\0'; +} diff --git a/external/libhv/libhv-1.3.2/util/md5.h b/external/libhv/libhv-1.3.2/util/md5.h new file mode 100644 index 0000000..9909856 --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/md5.h @@ -0,0 +1,25 @@ +#ifndef HV_MD5_H_ +#define HV_MD5_H_ + +#include "hexport.h" + +typedef struct { + unsigned int count[2]; + unsigned int state[4]; + unsigned char buffer[64]; +} HV_MD5_CTX; + +BEGIN_EXTERN_C + +HV_EXPORT void HV_MD5Init(HV_MD5_CTX *ctx); +HV_EXPORT void HV_MD5Update(HV_MD5_CTX *ctx, unsigned char *input, unsigned int inputlen); +HV_EXPORT void HV_MD5Final(HV_MD5_CTX *ctx, unsigned char digest[16]); + +HV_EXPORT void hv_md5(unsigned char* input, unsigned int inputlen, unsigned char digest[16]); + +// NOTE: if outputlen > 32: output[32] = '\0' +HV_EXPORT void hv_md5_hex(unsigned char* input, unsigned int inputlen, char* output, unsigned int outputlen); + +END_EXTERN_C + +#endif // HV_MD5_H_ diff --git a/external/libhv/libhv-1.3.2/util/sha1.c b/external/libhv/libhv-1.3.2/util/sha1.c new file mode 100644 index 0000000..fea5b69 --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/sha1.c @@ -0,0 +1,313 @@ +/* +SHA-1 in C +By Steve Reid +100% Public Domain + +Test Vectors (from FIPS PUB 180-1) +"abc" + A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D +"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" + 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 +A million repetitions of "a" + 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F +*/ + +/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */ +/* #define SHA1HANDSOFF * Copies data before messing with it. */ + +#define SHA1HANDSOFF + +#include +#include + +#include "sha1.h" + +#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) + +/* blk0() and blk() perform the initial expand. */ +/* I got the idea of expanding during the round function from SSLeay */ +#if BYTE_ORDER == LITTLE_ENDIAN +#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \ + |(rol(block->l[i],8)&0x00FF00FF)) +#elif BYTE_ORDER == BIG_ENDIAN +#define blk0(i) block->l[i] +#else +#error "Endianness not defined!" +#endif +#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ + ^block->l[(i+2)&15]^block->l[i&15],1)) + +/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ +#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); +#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); +#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); +#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); + +/* Hash a single 512-bit block. This is the core of the algorithm. */ + +void HV_SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] +) +{ + uint32_t a, b, c, d, e; + + typedef union + { + unsigned char c[64]; + uint32_t l[16]; + } CHAR64LONG16; + +#ifdef SHA1HANDSOFF + CHAR64LONG16 block[1]; /* use array to appear as a pointer */ + + memcpy(block, buffer, 64); +#else + /* The following had better never be used because it causes the + * pointer-to-const buffer to be cast into a pointer to non-const. + * And the result is written through. I threw a "const" in, hoping + * this will cause a diagnostic. + */ + CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer; +#endif + /* Copy context->state[] to working vars */ + a = state[0]; + b = state[1]; + c = state[2]; + d = state[3]; + e = state[4]; + /* 4 rounds of 20 operations each. Loop unrolled. */ + R0(a, b, c, d, e, 0); + R0(e, a, b, c, d, 1); + R0(d, e, a, b, c, 2); + R0(c, d, e, a, b, 3); + R0(b, c, d, e, a, 4); + R0(a, b, c, d, e, 5); + R0(e, a, b, c, d, 6); + R0(d, e, a, b, c, 7); + R0(c, d, e, a, b, 8); + R0(b, c, d, e, a, 9); + R0(a, b, c, d, e, 10); + R0(e, a, b, c, d, 11); + R0(d, e, a, b, c, 12); + R0(c, d, e, a, b, 13); + R0(b, c, d, e, a, 14); + R0(a, b, c, d, e, 15); + R1(e, a, b, c, d, 16); + R1(d, e, a, b, c, 17); + R1(c, d, e, a, b, 18); + R1(b, c, d, e, a, 19); + R2(a, b, c, d, e, 20); + R2(e, a, b, c, d, 21); + R2(d, e, a, b, c, 22); + R2(c, d, e, a, b, 23); + R2(b, c, d, e, a, 24); + R2(a, b, c, d, e, 25); + R2(e, a, b, c, d, 26); + R2(d, e, a, b, c, 27); + R2(c, d, e, a, b, 28); + R2(b, c, d, e, a, 29); + R2(a, b, c, d, e, 30); + R2(e, a, b, c, d, 31); + R2(d, e, a, b, c, 32); + R2(c, d, e, a, b, 33); + R2(b, c, d, e, a, 34); + R2(a, b, c, d, e, 35); + R2(e, a, b, c, d, 36); + R2(d, e, a, b, c, 37); + R2(c, d, e, a, b, 38); + R2(b, c, d, e, a, 39); + R3(a, b, c, d, e, 40); + R3(e, a, b, c, d, 41); + R3(d, e, a, b, c, 42); + R3(c, d, e, a, b, 43); + R3(b, c, d, e, a, 44); + R3(a, b, c, d, e, 45); + R3(e, a, b, c, d, 46); + R3(d, e, a, b, c, 47); + R3(c, d, e, a, b, 48); + R3(b, c, d, e, a, 49); + R3(a, b, c, d, e, 50); + R3(e, a, b, c, d, 51); + R3(d, e, a, b, c, 52); + R3(c, d, e, a, b, 53); + R3(b, c, d, e, a, 54); + R3(a, b, c, d, e, 55); + R3(e, a, b, c, d, 56); + R3(d, e, a, b, c, 57); + R3(c, d, e, a, b, 58); + R3(b, c, d, e, a, 59); + R4(a, b, c, d, e, 60); + R4(e, a, b, c, d, 61); + R4(d, e, a, b, c, 62); + R4(c, d, e, a, b, 63); + R4(b, c, d, e, a, 64); + R4(a, b, c, d, e, 65); + R4(e, a, b, c, d, 66); + R4(d, e, a, b, c, 67); + R4(c, d, e, a, b, 68); + R4(b, c, d, e, a, 69); + R4(a, b, c, d, e, 70); + R4(e, a, b, c, d, 71); + R4(d, e, a, b, c, 72); + R4(c, d, e, a, b, 73); + R4(b, c, d, e, a, 74); + R4(a, b, c, d, e, 75); + R4(e, a, b, c, d, 76); + R4(d, e, a, b, c, 77); + R4(c, d, e, a, b, 78); + R4(b, c, d, e, a, 79); + /* Add the working vars back into context.state[] */ + state[0] += a; + state[1] += b; + state[2] += c; + state[3] += d; + state[4] += e; + /* Wipe variables */ + a = b = c = d = e = 0; +#ifdef SHA1HANDSOFF + memset(block, '\0', sizeof(block)); +#endif +} + + +/* HV_SHA1Init - Initialize new context */ + +void HV_SHA1Init( + HV_SHA1_CTX * context +) +{ + /* SHA1 initialization constants */ + context->state[0] = 0x67452301; + context->state[1] = 0xEFCDAB89; + context->state[2] = 0x98BADCFE; + context->state[3] = 0x10325476; + context->state[4] = 0xC3D2E1F0; + context->count[0] = context->count[1] = 0; +} + + +/* Run your data through this. */ + +void HV_SHA1Update( + HV_SHA1_CTX * context, + const unsigned char *data, + uint32_t len +) +{ + uint32_t i; + + uint32_t j; + + j = context->count[0]; + if ((context->count[0] += len << 3) < j) + context->count[1]++; + context->count[1] += (len >> 29); + j = (j >> 3) & 63; + if ((j + len) > 63) + { + memcpy(&context->buffer[j], data, (i = 64 - j)); + HV_SHA1Transform(context->state, context->buffer); + for (; i + 63 < len; i += 64) + { + HV_SHA1Transform(context->state, &data[i]); + } + j = 0; + } + else + i = 0; + memcpy(&context->buffer[j], &data[i], len - i); +} + + +/* Add padding and return the message digest. */ + +void HV_SHA1Final( + unsigned char digest[20], + HV_SHA1_CTX * context +) +{ + unsigned i; + + unsigned char finalcount[8]; + + unsigned char c; + +#if 0 /* untested "improvement" by DHR */ + /* Convert context->count to a sequence of bytes + * in finalcount. Second element first, but + * big-endian order within element. + * But we do it all backwards. + */ + unsigned char *fcp = &finalcount[8]; + + for (i = 0; i < 2; i++) + { + uint32_t t = context->count[i]; + + int j; + + for (j = 0; j < 4; t >>= 8, j++) + *--fcp = (unsigned char) t} +#else + for (i = 0; i < 8; i++) + { + finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */ + } +#endif + c = 0200; + HV_SHA1Update(context, &c, 1); + while ((context->count[0] & 504) != 448) + { + c = 0000; + HV_SHA1Update(context, &c, 1); + } + HV_SHA1Update(context, finalcount, 8); /* Should cause a HV_SHA1Transform() */ + for (i = 0; i < 20; i++) + { + digest[i] = (unsigned char) + ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255); + } + /* Wipe variables */ + memset(context, '\0', sizeof(*context)); + memset(&finalcount, '\0', sizeof(finalcount)); +} + +void HV_SHA1( + char *hash_out, + const char *str, + uint32_t len) +{ + HV_SHA1_CTX ctx; + unsigned int ii; + + HV_SHA1Init(&ctx); + for (ii=0; ii> 4); + *output++ = i2hex(digest[i] & 0x0F); + } + if (outputlen > 40) *output = '\0'; +} diff --git a/external/libhv/libhv-1.3.2/util/sha1.h b/external/libhv/libhv-1.3.2/util/sha1.h new file mode 100644 index 0000000..3d74765 --- /dev/null +++ b/external/libhv/libhv-1.3.2/util/sha1.h @@ -0,0 +1,55 @@ +#ifndef HV_SHA1_H_ +#define HV_SHA1_H_ + +/* + SHA-1 in C + By Steve Reid + 100% Public Domain + */ + +/* for uint32_t */ +#include + +#include "hexport.h" + +typedef struct { + uint32_t state[5]; + uint32_t count[2]; + unsigned char buffer[64]; +} HV_SHA1_CTX; + +BEGIN_EXTERN_C + +HV_EXPORT void HV_SHA1Transform( + uint32_t state[5], + const unsigned char buffer[64] + ); + +HV_EXPORT void HV_SHA1Init( + HV_SHA1_CTX * context + ); + +HV_EXPORT void HV_SHA1Update( + HV_SHA1_CTX * context, + const unsigned char *data, + uint32_t len + ); + +HV_EXPORT void HV_SHA1Final( + unsigned char digest[20], + HV_SHA1_CTX * context + ); + +HV_EXPORT void HV_SHA1( + char *hash_out, + const char *str, + uint32_t len); + +HV_EXPORT void hv_sha1(unsigned char* input, uint32_t inputlen, unsigned char digest[20]); + +// NOTE: if outputlen > 40: output[40] = '\0' +HV_EXPORT void hv_sha1_hex(unsigned char* input, uint32_t inputlen, char* output, uint32_t outputlen); + +END_EXTERN_C + +#endif // HV_SHA1_H_